<?php

namespace app\wxapp\controller;

use app\lib\MiniProgramAccount;
use app\model\Modules;
use app\model\Record;
use app\model\Common;
use app\model\Util;
use app\model\Ad;
use app\model\Koi;
use app\model\Comm;
use app\model\Theme;
use app\model\Points;
use app\model\Bargain;
use app\model\Poster;
use app\model\Worker;
use app\model\Fans;
use app\model\Recordbase;
use app\model\Complain;
use app\model\Pay;
use app\model\Order;
use app\model\Userdata;
use app\model\W_input;
use app\model\Share;
use app\model\Relation;
use app\model\Game;
use app\model\Yxgifts;
use app\model\Scan;
use app\model\Otherform;
use app\model\Lottery;
use app\plugin\core\inc\PluginRoute;
use think\Db;
use think\Session;

class Entry extends Base
{
    public function oauth()
    {
        global $_P, $_G;

        if ($_P['a'] == 'getwxapp') {
            return self::GetUserHistory();
        }
//        session("username", "易宣888");
        $session_id = session_id();

        /**
         * *************************************************************
         * desc: 新增加逻辑，获取openid以及增加或更新用户信息
         * *************************************************************
         */
        $apiOpenidResult = MiniProgramAccount::getInstance()->getUserOpenidByCode();
        if (isset($apiOpenidResult['errcode']) && $apiOpenidResult['errcode']) {
            $err_data = ['code' => $apiOpenidResult['errcode'], 'msg' => $apiOpenidResult['errmsg']];
            yxlog($err_data, '小程序授权失败');
            exit(json_encode($err_data));
        }

        // 根据openid获取数据表中存在的用户信息
        $openid = $apiOpenidResult['openid'];
        // 将用户openid存入session
        session('openid', $openid);
//        session('package_id', 'hello, test123');

        // 根据openid获取用户在数据表中的记录
        $member_info = member_info($openid);
        // 用户记录不存在时将用户数据存入数据表
        if (empty($member_info)) {
            $user_avatar = '';
            $user_nickname = '';
            $insert_data = [
                'mpid' => $_G['mpid'],
                'openid' => $openid,
                'unionid' => '',
                'nickname' => $user_nickname,
                'avatar' => $user_avatar,
                'realname' => '',
                'mobile' => '',
                'updatetime' => time()
            ];
            $insert_res = member_save($insert_data);
            $insert_data['uid'] = $insert_res['uid'];
            $insert_data['is_auth'] = 0;
            unset($insert_data['unionid']);
            //挂载全局member
            $_G['member'] = $insert_data;
            //挂载全局uid
            $_G['uid'] = $insert_data['uid'];
            $_G['openid'] = $openid;
            // TODO update
            $_G['member'] = $member_info;
            $_G['openid'] = $openid;
        }

        $data = [
            "errno" => 0,
            "message" => "",
            "data" => [
                "sessionid" => $session_id, // 对应参数
                "member" => [
                    "uid" => $_G['member']['uid'], // 对应参数
                    "uniacid" => $_G['mpid'],
                    "mobile" => $_G['member']['mobile'],// 对应参数
//                    "email" => "",
//                    "groupid" => 0,
//                    "credit1" => 0,
//                    "credit2" => 0,
//                    "credit3" => 0,
//                    "credit4" => 0,
//                    "credit5" => 0,
//                    "credit6" => 0,
                    "createtime" => time(), // 参数不明确
                    "realname" => $_G['member']['realname'],// 对应参数
                    "nickname" => $_G['member']['realname'], // 对应参数
                    "avatar" => $_G['member']['realname'],// 对应参数
//                    "qq" => "",
//                    "vip" => 0,
//                    "gender" => 0,
//                    "birthyear" => 0,
//                    "birthmonth" => 0,
//                    "birthday" => 0,
//                    "constellation" => "",
//                    "zodiac" => "",
//                    "telephone" => "",
//                    "idcard" => "",
//                    "studentid" => "",
//                    "grade" => "",
//                    "address" => "",
//                    "zipcode" => "",
//                    "nationality" => "",
//                    "resideprovince" => "",
//                    "residecity" => "",
//                    "residedist" => "",
//                    "graduateschool" => "",
//                    "company" => "",
//                    "education" => "",
//                    "occupation" => "",
//                    "position" => "",
//                    "revenue" => "",
//                    "affectivestatus" => "",
//                    "lookingfor" => "",
//                    "bloodtype" => "",
//                    "height" => "",
//                    "weight" => "",
//                    "alipay" => "",
//                    "msn" => "",
//                    "taobao" => "",
//                    "site" => "",
//                    "bio" => "",
//                    "interest" => "",
//                    "pay_password" => "",
                ],
                "userinfo" => [
                    "fanid" => $_G['member']['uid'], // 参数不明确
                    "acid" => $_G['mpid'], // 参数不明确 mpid
                    "uniacid" => $_G['mpid'], // 参数不明确
                    "uid" => $_G['member']['uid'], // 对应参数
                    "openid" => $_G['member']['openid'], // 对应参数
                    "nickname" => $_G['member']['nickname'],// 对应参数
//                    "groupid" => "",
//                    "salt" => mt_rand(8), // 参数不明确
//                    "follow" => 1,
//                    "followtime" => time(),
//                    "unfollowtime" => 0,
                    "tag" =>
                        [
                            "subscribe" => 1,
                            "openid" => $_G['member']['openid'], // 对应参数
                            "nickname" => $_G['member']['nickname'], // 对应参数
                            "sex" => 0,
                            "language" => "",
                            "city" => "",
                            "province" => "",
                            "country" => "",
                            "avatar" => $_G['member']['avatar'], // 对应参数
                        ],

//                    "updatetime" => time(),
//                    "unionid" => "",
//                    "sex" => 0,
//                    "gender" => 0,
                    "headimgurl" => $_G['member']['avatar'],
                    "avatar" => $_G['member']['avatar'],
                ],
                "openid" => $_G['member']['openid']
            ]
        ];
        self::wx_result(0, '', array('sessionid' => $session_id, 'member' => $data['data']['member'], 'userinfo' => $data['data']['userinfo'], 'openid' => $_G['member']['openid']));
    }

    public function GetUserHistory()
    {
        global $_P, $_G;
        $do = $_P['do'];

        if (!empty($_P['openid'])) {
            $search_key = " WHERE openid ='" . trim($_P['openid']) . "'";
        }
        if (!empty($_P['uid'])) {
            $search_key = " WHERE uid ='" . trim($_P['uid']) . "'";
        }

        $sql = "SELECT module_name FROM `yx_sys_modules` where theme->>'$.title' is not null ORDER BY id desc";
        $modules = db_select($sql);
        $moduleslist = $modules;
        $result = array();
        foreach ($moduleslist as $index => $item) {
            $fans = db_find('SELECT * FROM ' . tablename($item['module_name'] . "_afans") . $search_key);
            if (!empty($fans)) {
                if ($fans['openid'] != $_P['openid']) {
                    break;
                } else {
                    $theme = db_find('SELECT * FROM ' . tablename($item['module_name'] . "_atheme") . " where id =" . $fans['themeid']);
                    if (!empty($theme)) {
                        $result['softname'] = $item['module_name'];
                        $result['themeid'] = $theme['id'];
                        $result['softkey'] = $theme['softkey'];
                        $result['fromuid'] = $fans['fromuid'];
                        $result['addtime'] = $fans['addtime'];
                        break;
                    }
                }
            }
        }
        if (!empty($_P['pdata'])) {
            self::wx_result(0, '', $result);
        } else {
            return_msg($result, '', 'ajax');
        }
    }

    function wx_result($error = 0, $msg = '', $data = null)
    {
        global $_GPC;
        if (!is_array($data)) {
            $data = [];
        }
        $result = json_encode(['errno' => $error, 'message' => $msg, 'data' => $data]);
        list ($t1, $t2) = explode(' ', microtime());
        $basecode = ( float )sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000) . mt_rand(1000, 9999);
        $txt = md5($basecode);
        $key = md5(date('md') . $txt);
        for ($i = 0; $i < 10; $i++) {
            $encode_txt = self::wx_authcode2($result, 'ENCODE', $key);
            $decode_txt = self::wx_authcode2($encode_txt, 'DECODE', $key);
            if (md5($decode_txt) === md5($result)) {
                //前32位为有无Softname判断mdY为有 Ymd没有,中间32位为数据MD5,后32位为随机key;
                $pdata = md5(date("Ymd")) . md5($encode_txt) . $txt . $encode_txt;
                $result = json_encode(array(
                    'pdata' => $pdata
                ));
                break;
            }
        }
        exit($result);
    }

//函数authcode($string, $operation, $key, $expiry)中的$string：字符串，明文或密文；$operation：DECODE表示解密，其它表示加密；$key：密匙；$expiry：密文有效期。
    function wx_authcode2($string, $operation = 'DECODE', $key = 'yixuan', $expiry = 0)
    {
        if ($operation == 'ENCODE') {
            $string = urlencode($string);
        }
        if ($operation == 'DECODE') {
            $md5 = substr($string, 0, 16) . substr($string, -16);
            $string = substr($string, 16, strlen($string) - 32);
            if ($md5 != md5($string)) {
                return;
            }
        }

        // 动态密匙长度，相同的明文会生成不同密文就是依靠动态密匙
        $ckey_length = 5;

        // 密匙
        $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);

        // 密匙a会参与加解密
        $keya = md5(substr($key, 0, 16));
        // 密匙b会用来做数据完整性验证
        $keyb = md5(substr($key, 16, 16));
        // 密匙c用于变化生成的密文
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
        // 参与运算的密匙
        $cryptkey = $keya . md5($keya . $keyc);
        $key_length = strlen($cryptkey);
        // 明文，前10位用来保存时间戳，解密时验证数据有效性，10到26位用来保存$keyb(密匙b)，
        //解密时会通过这个密匙验证数据完整性
        // 如果是解码的话，会从第$ckey_length位开始，因为密文前$ckey_length位保存 动态密匙，以保证解密正确
        $string = $operation == 'DECODE' ? utf8_decode(base64_decode(substr($string, $ckey_length))) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
        $string_length = strlen($string);
        $result = '';
        $box = range(0, 229);
        $rndkey = array();
        // 产生密匙簿
        for ($i = 0; $i <= 229; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }
        // 用固定的算法，打乱密匙簿，增加随机性，好像很复杂，实际上对并不会增加密文的强度
        for ($j = $i = 0; $i < 230; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 230;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }
        // 核心加解密部分
        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 230;
            $j = ($j + $box[$a]) % 230;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            // 从密匙簿得出密匙进行异或，再转成字符
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 230]));
        }
        if ($operation == 'DECODE') {
            // 验证数据有效性，请看未加密明文的格式
            if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
                return urldecode(substr($result, 26));
            } else {
                return '';
            }
        } else {
            // 把动态密匙保存在密文里，这也是为什么同样的明文，生产不同密文后能解密的原因
            // 因为加密后的密文可能是一些特殊字符，复制过程可能会丢失，所以用base64编码
            $result = $keyc . str_replace('=', '', base64_encode(utf8_encode($result)));
            $key = md5($result);
            return substr($key, 0, 16) . $result . substr($key, 16, 16);
        }
    }



//***********main方法调用************
//***********main方法调用************
//直接调用MOD类里的main函数，可通过op执行不同的操作，解决h5与wxapp使用一套代码的问题；
//调用说明：
//----参数do:仅限main,参数mod为模块名，主函数名称必须是main
//----可通过OP来控制调用哪个子函数
//----参数isworker：true会验证只有员工才可以防问，若需验证需要在main函数二次验证是否为员工，防止更改isworker参数跳过验证；
//返回数组说明：
//----值error:0正常，1错误
//----值msg:发生错误时的提示语
//----值data:返回给前端的所有数据
//----值jubf:版权信息
//----值jishu:版权信息
    public function Main()
    {
        global $_P, $_G;
        if (empty($_P['mod'])) {
            return_msg('路径错误！');
        }
        extract(self::Isworker(!empty($_P['isworker'])));
        $result = userdata::Main($system, $theme, $config, $fans, $themeid, $myworker);
        $this->jubf = $jubf;
        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg']);
        } else {
            $result['data']['jubf'] = $this->jubf;
            $result['data']['jishu'] = $jishu;
            wxapp_result(0, '', $result['data']);
        }
    }

    public function OnlyPay()
    {
        global $_P, $_G;
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $theme = Theme::getThemeByIdxcx($themeid);
        $fans = self::checkuser();
        $desclen = 26;
        if (!empty($theme['mobile'])) {
            $desc = "【客服" . $theme['mobile'] . "】";
            $desclen = $desclen - mb_strlen($desc);
        }
        if (!empty($theme['jubf'])) {
            $desc = mb_substr($theme['jubf'], 0, $desclen, "UTF-8") . $desc;
        } else {
            $desc = mb_substr($theme['title'], 0, $desclen, "UTF-8") . $desc;
        }
        $title = $desc;

        $order_sql = " select * from " . tablename(t_order) . " where themeid=$themeid and openid='{$fans['openid']}' and paystate=0 order by id desc";
        $item = db_find($order_sql);
        if ($item) {
            $params = array('isrecharge' => false);
            if ($system['send_mode'] == 1) {
                $params ['profit_sharing'] = 'Y';
            }
            $params ['themeid'] = $item['themeid'];
            $params ['uniontid'] = $item['uniontid'];
            $params ['tid'] = $item['tid'];
            $params ['user'] = $item['openid'];
            $params ['fee'] = $item['orderfee'];
            $params ['title'] = $title;
            $params ['ordersn'] = $item['ordersn'];
            $params ['virtual'] = false;
            $params ['orderid'] = $item['id'];
        } else {
            wxapp_result(1, '未找到订单信息');
        }
        $pay_params = $this->pay($params);

        $pay_params ['pn_wxapp'] = $system['pn_wxapp'] == 1 ? 2 : 1;
        $pay_params ['jump_webview'] = Poster::createWxappUrl('mypay', array('themeid' => $themeid));

        if (is_error($pay_params)) {
            return wxapp_result(1, '支付失败：' . $pay_params['message'], $pay_params);
        }
        return wxapp_result(0, '', $pay_params);
    }


    public function videotime()
    {

        global $_P, $_G;
        $themeid = intval($_P['themeid']);
        if ($themeid < 1) {
            wxapp_result(1, '活动入口不正确');
        }
        $config = Theme::getConfig($themeid, true);
        $config['videotime'] = trim($_P['videotime']);
        Theme::setConfig($config, $themeid, $_G['mpid']);
        wxapp_result(0, '保存成功');
    }

    public function Share()
    {

        global $_P, $_G;
        $fans = self::checkuser();
        $themeid = intval($_P['themeid']);
        $theme = Theme::getThemeById($themeid);
        $system = $_G['system'];
        $config = Theme::getConfig($themeid);
        Common::share($system, $theme, $config, $fans, $themeid, 'friend');
        $result = self::share_main($system, $theme, $config, $fans, $themeid, 'Share');

        wxapp_result($result['err'], $result['msg'], $result['data']);
    }

    public function share_moments()
    {
        global $_P, $_G;
        $fans = self::checkuser();
        $themeid = intval($_P['themeid']);
        $theme = Theme::getThemeById($themeid);
        $system = $_G['system'];
        $config = Theme::getConfig($themeid);
        Common::share($system, $theme, $config, $fans, $themeid, 'moments');
        $result = self::share_main($system, $theme, $config, $fans, $themeid, 'share_moments');
        wxapp_result($result['err'], $result['msg'], $result['data']);
    }

    protected function share_main($system, $theme, $config, $fans, $themeid, $op)
    {
        global $_G, $_P;
        $workerid = intval($_P['workerid']);
        $pw = array(":workerid" => $workerid);
        $p = array(":themeid" => $themeid);
        $pm = array(":themeid" => $themeid, ":openid" => $_G['openid']);
        if (DOMAIN0 == "30.yixuan.net") {
            $theme['endtime'] = TIMESTAMP + 86400;;
            $theme['status'] = 1;
        }
        $endime1 = $theme['endtime'];
        if ($endime1 < TIMESTAMP || $theme['status'] != 1) {
            return array('err' => 1, 'msg' => '活动已经结束啦，感谢您的支持');
        }

        db_query("UPDATE " . tablename(t_theme) . " SET forward = forward +1 WHERE id =:themeid", $p);
        db_query("UPDATE " . tablename(t_report) . " SET forward = forward +1 WHERE software = '" . MODULE_NAME . "' and themeid =:themeid and riqi ='" . date("Y-m-d") . "'", $p);
        if (!empty($_G['openid'])) {
            db_query("UPDATE " . tablename(t_fans) . " SET forward = forward +1 WHERE themeid =:themeid and openid = :openid", $pm);
        }
        if (!empty($workerid)) {
            db_query("UPDATE " . tablename(t_worker) . " SET forward = forward +1 WHERE themeid = " . $themeid . " and uid =:workerid", $pw);
        }
        Theme::workerreport($themeid, $workerid, array('forward' => 1));

        if (!empty($_G['member']['uid']) && $op == 'share_moments') {
            $fromuid = $_P['fromuid'];
            $data = array(
                'uniacid' => $_G['mpid'],
                'themeid' => $themeid,
                'openid' => $_G['openid'],
                'uid' => $_G['member']['uid'],
                'addtime' => TIMESTAMP,
                'status' => 0,
                'workerid' => $workerid,
                'fromuid' => $fromuid,
            );

            if ($system['hdget'] == 1) {
                if (Fans::getuid_old($fromuid, $themeid)) {
                    $data['fromuid_old'] = $fromuid;
                }
                if (Fans::getuid_old($workerid, $themeid)) {
                    $data['workerid_old'] = $workerid;
                }
            }

            $yaoyiyao = floatval(db_fetchcolumn('SELECT sum(fee) FROM ' . tablename(t_commshare) . "
WHERE themeid = '{$themeid}' and status <2 and uid ='{$_G['member']['uid']}'"));

            $todaylight = intval(db_fetchcolumn("SELECT COUNT(*) FROM " . tablename(t_share) . "
WHERE themeid =:themeid and openid = :openid and status = 1 and addtime > " . strtotime(date('Y-m-d')), $pm));

            if (($yaoyiyao > 0 || $config['isicon'] > 0 || $config['fanpaigroupid'] > 0) && $todaylight < $config['todayicon']) {
                $data['status'] = 1;
            }
            $insertid = db_insert(t_share, $data);

            if ($config['isicon'] == 1) {
                $lightsum = Scan::getlightsum($config, $themeid, $_G['openid'], $_G['member']['uid']);
                $light_list = Share::get_light_list($config, $lightsum);
            }
            $ishasinfo = 0;
            if ($config['isicon'] > 0 && $config['isicon'] != 3 && !empty($_G['openid'])) {
                $p3 = array(":uid" => $_G['member']['uid'], ":themeid" => $themeid);
                $recordinfo = db_find("SELECT * FROM " . tablename(t_record) . "
WHERE themeid =:themeid
and (uid = :uid or uid_other =:uid)  order by id desc limit 1", $p3);
                if (empty($recordinfo)) {
                    if ($config['comm4ziliao'] == 1 || $config['isicon'] > 0 && $config['iconziliao'] != 1) {
                        $ishasinfo = 1;
                    }
                }

            }
        }
        $light_list['isicon'] = $config['isicon'];
        return array('err' => 0, 'msg' => '成功', 'data' => array('uid' => $_G['member']['uid'], 'workerid' => $workerid, 'status' => $data['status'], 'light_list' => $light_list, 'ishasinfo' => $ishasinfo));
    }

    public function Searchorder()
    {
        global $_P, $_G;
        $mobile = trim($_P['search_txt']);
        if (empty($mobile)) {
            wxapp_result(1, '手机未输入');
        }
        $themeid = intval($_P['themeid']);
        if ($themeid < 1) {
            wxapp_result(1, '活动入口不正确');
        }

        $config = Theme::getConfig($themeid);

        $result = array();
        $sql = "SELECT * FROM " . tablename(t_record) . "
WHERE themeid =:themeid and mobile = :mobile  and status > 0";
        $record = db_find($sql, array(":themeid" => $themeid, ":mobile" => $mobile));
        if ($config['isrecent'] >= 1) {
            if (!empty($record)) {
                $result['errcode'] = 1;
                $result['recordid'] = $record['pid'];
                $result['fromuid'] = $record['uid'];
                $result['workerid'] = $record['workerid'];
                if ($config['tuanmode'] == 0) {
                    $result['isfinish'] = $record['isfinish'];
                } elseif ($config['tuanmode'] == 1) {
                    $result['isfinish'] = 0;
                }
            } else {
                $result['errcode'] = 0;
                $result['msg'] = '手机' . $mobile . '未搜到';
            }
        } else {
            if (!empty($record)) {
                $result['errcode'] = 0;
                $result['msg'] = '手机' . $mobile . '已支付!';
            } else {
                $result['errcode'] = 0;
                $result['msg'] = '手机' . $mobile . '未支付!';
            }
        }
        wxapp_result(0, '成功', $result);
    }


//入口参数
    public function Scene()
    {
        global $_P, $_G;

        // 测试代码
//        $openid = session('openid');
//        $debugString = 'session中openid获取到的数据为:' . $openid;
//        echo $debugString;

//        yxlog('获取到的package_id在session中的值为:' . session('package_id'));
//        yxlog($_G);
        $_G['member']['uid'] = Fans::getRealUid();
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $recordid = intval($_P['recordid']);
        $theme = Theme::getThemeByIdxcx($themeid);
        $config = Theme::getConfig($themeid);
        $fromuid = $_P['fromuid'];
        $path = intval($_P['path']);
//        $fans = self::checkuser();
        $pm = array(":themeid" => $themeid, ":openid" => $_G['openid']);
        $fans = db_find("SELECT * FROM " . tablename(t_fans) . "
WHERE themeid = :themeid and openid = :openid", $pm);
        if (empty($theme['id'])) {
            wxapp_result(1, '活动入口不正确');
            exit;
        }
        if (!empty($fromuid)) {
            if (strtolower(substr($fromuid, 0, 1)) == 'p') {
                $path = intval(substr($fromuid, 1));
            }
        }
        if ($path > 0) {
            $relation = db_get(t_userdata_relation, array('id' => $path));
            $fromuid = $relation['from_uid'];
            $workerid = $relation['workerid'];
            if ($config['is_tuan_order'] == 1) {
                $recordid = $relation['recordid'];
            }
        }
        if ($system['ruanjian'] == 10) {
            $weikeid = intval($_P['wk_id']);
            if (!empty($fromuid)) {
                if (strtolower(substr($fromuid, 0, 1)) == 'w') {
                    $weikeid = intval(substr($fromuid, 1));
                }
            }
            if ($weikeid > 0) {
//查找fromuid
                $wkinfo = db_get(wk_info, array('id' => $weikeid));
                $wk_config = json_decode($wkinfo['config'], true);
                if (strtolower(substr($fromuid, 0, 1)) == 'w') {
                    $fromuid = $wkinfo['uid'];
                } else {
                    $fromuid = intval($_P['fromuid']);
                }
                $wkuid = $wkinfo['uid'];
                $workerid = intval($wk_config['workerid']);
                $recordid = $wkinfo['recordid'];
            }
        }
        if (empty($workerid) && !empty($fromuid)) {
            $reload_arr = Relation::getByThemeUid($themeid, $fromuid);
            $workerid = $reload_arr['workerid'];
        }

        if (!empty($theme['blacklist'])) {
            if (!empty($fromuid)) {
                if (strstr($theme['blacklist'] . "|", "|" . $fromuid . "|") !== false) {
                    $txt = !empty($theme['mobile']) ? '咨询电话：' . $theme['mobile'] : '';
                    $txt = "活动暂停，给您带来的不便还望凉解；" . $txt;
                    wxapp_result(1, $txt);
                    exit;
                }
            }
        }

        $p = array(":fromuid" => $fromuid, ":themeid" => $themeid);
        $sql = "SELECT * FROM " . tablename(t_fans) . "
WHERE themeid = :themeid and uid = :fromuid";
        $fans_from = db_find($sql, $p);

        $from_worker = Worker::getThemeWorkerByOpenid($fans_from['openid'], $themeid, 1);
        if (!empty($from_worker) && $from_worker['level'] <= 3) {
//            if (!(($_P['scene']==1047 || $_P['scene']==1048) && $config['is_tuan_order']==1)){
//                $recordid = 0;
//            }
            if ($config['is_tuan_order'] != 1 && $recordid != 99999 && $recordid > 0) {
                $recordid = 0;
                $_P['recordid'] = 0;
                Userdata::addLog($themeid, $_G['member']['uid'], 39, '推荐者为员工,清空拼团信息');
            }
            $workerid = $from_worker['uid'];
        } else {
//如果是砍价的活动则取砍价定单
            if ($system['ruanjian'] == 5) {
                $recordid = Bargain::getUserRecordid($themeid, $fans_from['uid']);
                $themyrecord = Record::getById($recordid);
                $workerid = $themyrecord['workerid'];
            } else {
//如果付款显示当前团
                $themyrecord = Record::getLastGroupByUid($fans_from['uid'], $themeid);
                if (!empty($themyrecord)) {
                    if ($themyrecord['type'] == 1) {
                        $recordid = $themyrecord['pid'];
                    } else {
                        $recordid = $themyrecord['id'];
                    }
                    $workerid = $themyrecord['workerid'];
                }
            }
        }


        if (empty($workerid)) {
            $workerid = $fans_from['workerid'];
        }

        if ($system['live'] == 1 && $config['livedata']['yure'] == 1) {
            $theme['endtime'] = $config['livedata']['livetime'];
        }

        $goto_mystery_boxes_feichi = '';
        if ($system['is_mystery_boxes_feichi'] == 1) {
            $self = Ad::getSelfInfo($fans, $config, $themeid, $system);
            if ($self['is_get_box']) {
                $goto_mystery_boxes_feichi = 'my';
            }

            if ($fromuid != $_G['member']['uid'] && !empty($fromuid)) {
                $friend = Ad::getFriendInfo($fromuid, $config, $themeid, $system);
                if ($friend['is_get_box']) {
                    $goto_mystery_boxes_feichi = 'friend';
                }
            }
        }

//新样式抽奖判断
        $jump_lottery = '';
        $is_lottery = $system['lottery'];
        if ($config['yx_lt_mode'] == 1 && $is_lottery && TIMESTAMP > $config['yx_lt_begintime']) {
            $is_lottery = 2;

            require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
            require_once get_path('plugin/lottery/core/model.php');
//判断有无上一级
            $from_uid = intval($_P['fromuid']);
            $uid = $fans['uid'];
            if ($uid != $from_uid && $from_uid) {
//有上级
                $jump_lottery = 'friend';
            } else {
//无上级
//判断是否已支付
                $themyrecord = Record::getLastGroupByUid($fans['uid'], $themeid);
                if (!$themyrecord) {
                    \LotteryModel::initInfo($themeid, $config, $uid, $fromuid);
                }
                $remain_num = $fans['jihui'];
                $user_chance_flag_num = \LotteryModel::getUserChanceByUidAndThemeId($uid, $themeid);
                if ($remain_num > 0 || $user_chance_flag_num > 0) {
                    $jump_lottery = 'my';
                }
//判断是否有抽奖机会
            }
        }

//教培webview
        $jump_webview = '';
        $pn_wxapp = false;
//伪小程序
        if ($system['pn_wxapp']) {
            $jump_webview = Poster::createWxappUrl('index', array('themeid' => $themeid));
//判断分享条件  返回的pn_wxapp  1启用分享  2禁用分享 该字段 必须为真
            $pn_wxapp = 1;
            if ($system['pn_wxapp'] == 1) {
                $pn_wxapp = 2;
            } elseif ($system['pn_wxapp'] == 3) {
//判断是否存在支付订单
                $themyrecord = Record::getLastGroupByUid($uid, $themeid);
//判断员工
                $myworker = Worker::getThemeWorkerByOpenid($_G['openid'], $themeid, 1);
                if (!$myworker && !$themyrecord) {
                    $pn_wxapp = 2;
                }
            }
        }


//$system_new 待删除
        $system_new = array(
            'oem' => $_G['companyname'] == '金策软件' && $system['is_mystery_boxes'] == 1 ? '金策' : $_G['companyname'],
            'ruanjian' => $system['ruanjian'],
            'iskoi' => $system['iskoi'] && $config['koi_lottery_main'] ? 1 : 0,
            'is_lz_game' => $system['is_lz_game'] && $config['game_on_off'] ? 1 : 0,
            'is_lz_comment' => $system['is_lz_comment'] && $config['comment_on_off'] ? 1 : 0,
            'is_lottery' => $is_lottery,
        );


        if ($system['iskoi'] == 1 || $system['is_lz_game'] == 1) {
            $system_new['lz_game_img'] = $config['lz_game_img']; //拼团首页【进入游戏】Banner图
            $system_new['lz_game_img_position'] = $config['lz_game_img_position']; //拼团首页【进入游戏】显示位置
            $system_new['enter_lz_game_icon'] = $config['enter_lz_game_icon'];
            $system_new['koi_top_img'] = $config['koi_top_img'];

            $five_theme = Game::getThemeListByType('five_koi', $themeid);
            if ($five_theme['type_theme_total'] > 0) {
                $new_theme = Theme::getThemeById($five_theme['type_theme_list'][0]['id']);
                $fans_temp = Fans::getworkerid_fromuid($themeid, $fans_from);
                $workerid = $fans_temp['workerid'];
                $fromuid = $fans_temp['fromuid'];
                $xcxurl = '/pages/index/index?softname=' . MODULE_NAME . '&themeid=' . $new_theme['id'] . '&softkey=' . $new_theme['softkey'] . '&fromuid=' . $fromuid . '&workerid=' . $workerid;
                $system_new['koi_page_path'] = $xcxurl;
                $system_new['enter_koi_icon'] = $config['pintuan_to_koi_icon'];
            }
        }

//如果获取到了手机号则关闭
        if (!isset($config['getmobile'])) {
            $config['getmobile'] = 2;
        }
        if (!isset($config['getavatar'])) {
            $config['getavatar'] = 1;
        }
        if ($config['getmobile'] > 0 && $fans['mobile'] != '' || $theme['status'] == 2 || TIMESTAMP > $theme['endtime']) {
            $config['getmobile'] = 0;
        }
        $avatar_default = 'https://css2020.yixuan.net/2020css/yx2020/images/question.png';
        if ($config['getavatar'] > 0 && ($fans['avatar'] != '' && $fans['nickname'] != '' && $fans['avatar'] != $avatar_default && $fans['nickname'] != '新用户' && $fans['nickname'] != '微信用户')) {
            $config['getavatar'] = 0;
        }
        Userdata::addLog($themeid, $_G['member']['uid'], 1, '', $workerid, $fromuid, $_P['scene'], $path);

//如果为身份为员工，打开所有人都为自已
        $myworker = Worker::getThemeWorkerByOpenid($_G['openid'], $themeid, 1);
        if (!empty($myworker) && $myworker['level'] <= 3) {
            $workerid = $_G['member']['uid'];
            $recordid = $recordid != 99999 ? 0 : 99999;
            $fromuid = $_G['member']['uid'];
            $path = Userdata::MyPath($themeid, $_G['member']['uid'], $_G['member']['uid'], 0);
        }


        $result = array();
        $result['goto_mystery_boxes_feichi'] = empty($config['mystery_help_first_view']) ? $goto_mystery_boxes_feichi : 'home';
        $result['recordid'] = intval($_P['recordid']) == 99999 ? 99999 : $recordid;
        $result['system'] = $system_new;
        $result['workerid'] = $workerid;
        $result['jump_lottery'] = $jump_lottery;
        $result['jump_webview'] = $jump_webview;
        $result['pn_wxapp'] = $pn_wxapp;
        $result['fromuid'] = $fromuid;
        $result['path'] = $path;
        $result['system']['ruanjian'] = $system['ruanjian'];
        $result['yixuanadimg'] = 'http://oa.yixuan.net/yixuanad02.png';

        if ($system['ruanjian'] == 10) {
            $result['wkuid'] = $wkuid;
            $result['wk_id'] = $weikeid;
            if ($weikeid) {
//            $fans = self::checkuser();
                $result['workerid'] = intval($wk_config['workerid']);
                $result['recordid'] = $wkinfo['recordid'];
            }
        }
//隐私协议判断类型  true 隐藏模式  false显示模式、检察员模式
//隐私协议拒绝是否退出  true 退出  false 隐藏

        $result = array_merge($result, Common::GetWxappScene($system, $theme, $config, $fans, $themeid));

        wxapp_result(0, '成功', $result);
    }


    public function ShareInfo()
    {
        global $_P, $_G;
        $fans = self::checkuser();
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $config = Theme::getConfig($themeid);
        $theme = Theme::getThemeByIdxcx($themeid);
        $shareInfo = Common::getshareinfo($system, $theme, $config, $fans, '', '');
        $config_new = array(
            'formcolortop' => $config['formcolortop'],
            'formcolorrighttext' => $config['formcolorrighttext'],
            'pageshare' => $config['pageshare'],
            'centerimgs' => $config['centerimgs'],
            'headlogo' => $theme['headlogo'],
            'bannerimgs' => $config['bannerimgs'],
            'pageshare_topimg' => $config['pageshare_topimg'],
        );
        wxapp_result(0, '', array('shareinfo' => $shareInfo, 'config' => $config_new));
    }

    /**
     * Desc:用户广告点击事件
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/1 17:01
     */
    public function AdSubInfo()
    {
        global $_P, $_G;
        $fans = self::checkuser();
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $config = Theme::getConfig($themeid);
        $theme = Theme::getThemeByIdxcx($themeid);
        $from_uid = intval($_P['fromuid']);
        $res = Ad::fansSubInfo($system, $config, $themeid, $fans, $from_uid);
        if ($res['get_coupon']) {
            wxapp_result(1, '领取成功,请刷新或重新进入小程序', ['get_coupon' => $res['get_coupon']]);
        } else {
            wxapp_result(0, '操作成功', ['get_coupon' => $res['get_coupon']]);
        }
    }


//public function theme() {
//    global $_P, $_G;
//    $themeid = intval($_P['themeid']);
//    $theme = Theme::getThemeByIdxcx($themeid);
//    if(empty($theme['id'])){
//        wxapp_result(1, '活动入口不正确');
//        exit;
//    }
//    $result =  array();
//    $result['theme']=$theme;
//    wxapp_result(0, '成功', $result);
//}
    protected function systemnew($system)
    {
        $systemnew = array();
        $systemnew['live'] = $system['live'];
        $systemnew['live_lottery'] = $system['live_lottery'];
        $systemnew['livetemplate'] = $system['livetemplate'];
        $systemnew['fenxiao01'] = $system['fenxiao01'];
        $systemnew['fenxiao04'] = $system['fenxiao04'];
        $systemnew['fenxiao05'] = $system['fenxiao05'];
        $systemnew['fenxiao06'] = $system['fenxiao06'];
        $systemnew['fenxiao07'] = $system['fenxiao07'];
        $systemnew['ruanjian'] = $system['ruanjian'];
        return $systemnew;
    }


//更新用户手机号 新版本
    public function UpdateUserPhone()
    {
        global $_P, $_G;
        $themeid = intval($_P['themeid']);
        $system = $_G['system'];
        $_G['member']['uid'] = Fans::getRealUid();
//新版本解密手机号
        $uniacid = $_G['mpid'];
        if (!$_G['member']['uid']) {
            wxapp_result(1, '用户登录状态错误');
        }
        if (!$uniacid || $_P['op'] != 'getphone') {
            wxapp_result(1, '参数缺失');
        }
        $res = Modules::getPlatform($uniacid);
        if (!$res || $res['platform_type'] != 1) {
            wxapp_result(1, '小程序记录不存在');
        }
        $loginCode = $_P['code'] ? $_P['code'] : '';
        if (!$loginCode) {
            wxapp_result(1, '参数缺失');
        }
        $phoneinfo = self::getPhoneNumber($system, $loginCode);
        if (!empty($phoneinfo['data']['phoneNumber'])) {
            db_update('yx_sys_members', array('mobile' => $phoneinfo['data']['phoneNumber']), array('uid' => $_G['member']['uid']));
            $fans['mobile'] = $phoneinfo['data']['phoneNumber'];
//判断用户是否存在手机号的日志记录
            $check_has_userLog = db_get(t_userdata_record, ['uid' => $_G['member']['uid'], 'type' => 36, 'themeid' => $themeid]);
            if (!$check_has_userLog) {
                $fromuid = $_P['fromuid'];
                $workerid = $_P['workerid'];
//用户抽奖日志收集
                Userdata::addLog($themeid, $_G['member']['uid'], 36, $phoneinfo['data']['phoneNumber'], $workerid, $fromuid);
            }
        } else {
            yxlog($phoneinfo, '手机号授权失败');
        }
        $fans = member_info($_G['openid']);
        $fans['mobile'] = $phoneinfo['data']['phoneNumber'];
        $member = $fans;
        unset($member['password']);
        unset($member['salt']);
        wxapp_result(0, '', array('sessionid' => $_G['session_id'], 'member' => $member, 'userinfo' => $fans, 'openid' => $_G['openid']));
    }


    protected function getPhoneNumber($system, $code)
    {
//        $access_token = Poster::getAccessToken($system);
//        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$access_token;
//        $data = $this->curl($url,json_encode(['code'=>$code]),array('Content-Type: application/json'));

        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
        $postdata['code'] = $code;
        $res = PostByAccessToken($system, $url, $postdata);


        $data = json_decode($res, true);
        if ($data['errcode'] != 0) {
            return ['code' => $data['errcode'], 'msg' => $data['errmsg'], 'data' => []];
        } else {
            return ['code' => 0, 'msg' => 'ok', 'data' => $data['phone_info']];
        }

    }

    /**
     * Desc:获取优惠券信息
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/11/15 16:52
     */
    public function CouponInfo()
    {
        global $_P, $_G;
        $op = $_P['op'];
        $id = $_P['id'];
        $fans = self::checkuser();
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $config = Theme::getConfig($themeid);
        $theme = Theme::getThemeByIdxcx($themeid);
        $mode1 = ['url' => 991, 'page' => "/pages/mypay/mypay?softname=" . MODULE_NAME . "&themeid=" . $themeid . "&softkey=" . $theme['softkey'] . "&uid=" . $_G['member']['uid'], 'mode' => 1];
        $mode2 = ['url' => 992, 'function' => 'viewMypay', 'options' => 0];
        $mode3 = ['url' => 993, 'page' => Poster::createWxappUrl('mypay', array('themeid' => $themeid)), 'mode' => 0];

        require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
        require_once get_path('plugin/coupon/core/model.php');

        if ($op == 'display') {
            $top = \CouponModel::userCouponFlagList($themeid, $fans['uid'], $config);
            $center = [];
            $bottom = ['txt' => '关闭', 'action' => ''];
            $tips = '';
            if (count($top) > 1) {
                $tips = $config['coupon_mode_desc'];
            }
            $res = [
                'title' => '我的优惠券',
                'top' => $top,
                'center' => $center,
                'bottom' => $bottom,
                'tips' => $tips
            ];
//            $res = [
//                'title'=>'我的优惠券',
//                'top'=>[
////                    ['amount'=>'12.88元',
////                        'total_amount'=>'12.88元已提现',
////                        'icon'=>'https://css2020.yixuan.net/2020css/plugin/lottery/images/bag.png',
////                        'tips'=>'我的红包',
////                        'btm_txt'=>'全部已提现',
////                        'action'=>'',
////                        'diy_jump'=>$mode1,
////                    ],
////                    ['amount'=>'12.88元',
////                        'total_amount'=>'12.88元已提现',
////                        'icon'=>'https://css2020.yixuan.net/2020css/plugin/lottery/images/bag.png',
////                        'tips'=>'我的红包',
////                        'btm_txt'=>'全部已提现',
////                        'action'=>'',
////                        'diy_jump'=>$mode2,
////                    ],
////                    ['amount'=>'12.88元',
////                        'total_amount'=>'12.88元已提现',
////                        'icon'=>'https://css2020.yixuan.net/2020css/plugin/lottery/images/bag.png',
////                        'tips'=>'我的红包',
////                        'btm_txt'=>'全部已提现',
////                        'action'=>'',
////                        'diy_jump'=>$mode3,
////                    ]
//                ],
//                'center'=>[
////                    [
////                        'img'=>'http://img2020.yixuansoft.cn/images/2/2021/07/ZB8253B5JgIizgIfXZJsrXg5588RrJ.jpg/99.jpg',
////                        'title'=>'四等奖 回家睡大觉',
////                        'target_id'=>'12',
////                        'btn_txt'=>'待核销',
////                        'time'=>'2022=11-07 11:30:34',
////                        'action'=>'duihuan',
////                        'diy_jump'=>'',
////                    ],
////                    [
////                        'img'=>'https://dpy01cdn.yixuan.net/images/2/2021/04/nfYMpyuxB4Lf90YLcqVujXqMVUf6fP.png',
////                        'title'=>'三等奖 回家睡大觉',
////                        'target_id'=>'14',
////                        'btn_txt'=>'已核销',
////                        'time'=>'2022=11-07 11:30:34',
////                        'action'=>'',
////                        'diy_jump'=>$mode1,
////                    ],
////                    [
////                        'img'=>'http://img2020.yixuansoft.cn/images/2/2021/07/ZB8253B5JgIizgIfXZJsrXg5588RrJ.jpg/99.jpg',
////                        'title'=>'四等奖 回家睡大觉',
////                        'target_id'=>'12',
////                        'btn_txt'=>'待核销',
////                        'time'=>'2022=11-07 11:30:34',
////                        'action'=>'',
////                        'diy_jump'=>$mode2,
////                    ],
////                    [
////                        'img'=>'https://dpy01cdn.yixuan.net/images/2/2021/04/nfYMpyuxB4Lf90YLcqVujXqMVUf6fP.png',
////                        'title'=>'三等奖 回家睡大觉',
////                        'target_id'=>'14',
////                        'btn_txt'=>'已核销',
////                        'time'=>'2022=11-07 11:30:34',
////                        'action'=>'',
////                        'diy_jump'=>$mode3,
////                    ]
//                ],
//                'bottom'=>[
//                    'txt'=>'去打怪兽',
//                    'action'=>''
//                ],
//                'tips'=>'这是一点底部提示语'
//            ];
        } else {
            $coupon_item = db_get(t_yx_coupon, ['themeid' => $themeid, 'id' => $id]);
            $res = [
                'back_img' => 'https://css2020.yixuan.net/2020css/plugin/lottery/images/lessonBg.png',
                'prize_img' => $coupon_item['img'],
                'title' => '恭喜您获得一张优惠券',
                'prize_name' => $coupon_item['name'],
                'convert_card_title' => '兑奖凭证',
                'convert_card' => 'http://img2020.yixuansoft.cn/images/poster/2022-11/yx18900/4a0c7cca7083ea2318de2af4022b2dc7.png',
                'method' => '易宣软件测试专用',
                'tel' => '电话：13360646365',
                'address' => '地址：市北区长安镇万科广场',
                'btn_txt' => '我已知晓',
                'btm_tips' => '温馨提示：请妥善保管兑奖凭证，手机用户可截图保存',
//                'convert_card_title'=>'兑奖凭证',
//                'convert_card'=>'http://img2020.yixuansoft.cn/images/poster/2022-11/yx18900/4a0c7cca7083ea2318de2af4022b2dc7.png',
//                'method'=>'易宣软件测试专用',
//                'tel'=>'电话：13360646365',
//                'address'=>'地址：市北区长安镇万科广场',
//                'btn_txt'=>'已到店出示核销二维码',
//                'btm_tips'=>'温馨提示：请妥善保管兑奖凭证，手机用户可截图保存',
                'click_btm_close' => 1
            ];
        }

        wxapp_result(0, '', $res);
    }


    public function UpdateUserProfile()
    {
        global $_P, $_G;
        if (!empty($_G['uid'])) {
            $data = array();
            $data['nickname'] = $_P['nickname'];
            $data['avatar'] = $_P['avatarUrl'];
            $data['mobile'] = $_P['mobile'] && $_P['mobile'] != 'undefined' ? $_P['mobile'] : '';
            db_update('yx_sys_members', $data, array('uid' => $_G['uid']));
        }
        $member = member_info($_G['uid']);
        self::updateFansinfo($member);
    }

    public function updateFansinfo($member = '')
    {
        global $_P, $_G;
        $fans = self::checkuser($member);
        yxlog($fans, 'fans');
        $themeid = intval($_P['themeid']);
        $data = array();
        $system = $_G['system'];

//如果是砍价的活动则取砍价定单
        if ($system['ruanjian'] == 5) {
            $recordid = Bargain::getUserRecordid($themeid, $fans['uid']);
        } else {
            $themyrecord = Record::getLastGroupByUid($fans['uid'], $themeid);
            if (!empty($themyrecord)) {
                $data['isorder'] = 1;
                if ($themyrecord['type'] == 1) {
                    $recordid = $themyrecord['pid'];
                } else {
                    $recordid = $themyrecord['id'];
                }
            } else {
                $data['isorder'] = 0;
            }
        }

        if (!empty($themeid)) {
            $theme = Theme::getThemeByIdxcx($themeid);
            $config = Theme::getConfig($themeid);
            $shareinfo = Theme::getshareinfo($system, $theme, $config, $fans, '', '', $recordid);

//判断当前活动是否为宝妈拼拼看
            if ($_P['page'] == 'game' && !empty($config['five_themeid'])) {
                $data['share_time_line'] = $shareinfo;
//判断当前用户的关卡 1-3跳转无锦拼霸王
                $user_level_detail = Game::getGameUserDetail($themeid, $fans['uid']);
                $current_level = $user_level_detail['current_level'];
                if (empty($current_level) || $current_level < 4) {
                    $theme = Theme::getThemeById($config['five_themeid']);
                    $config = Theme::getConfig($config['five_themeid']);
                    $shareinfo = Theme::getshareinfo($system, $theme, $config, $fans, '', '', $recordid);
                }

            }
            $data['shareinfo'] = $shareinfo;
        }
        if (empty($member)) {
            $member = member_info($fans['uid']);
            unset($member['password']);
            unset($member['salt']);
        }
        $data['sessionid'] = $_G['session_id'];
        $data['member'] = $member;
        $data['userinfo'] = $fans;
//新增返回字段 冗余判断条件
        $data['getavatar'] = $config['getavatar'];
        $avatar_default = 'https://css2020.yixuan.net/2020css/yx2020/images/question.png';
        if ($config['getavatar'] > 0 && ($fans['avatar'] != '' && $fans['avatar'] != $avatar_default && $fans['nickname'] != '新用户' && $fans['nickname'] != '微信用户')) {
            $data['getavatar'] = 0;
        }
        wxapp_result(0, '', $data);
        exit;
    }

//入口参数
    public function Isworker($isworker = true)
    {
        global $_P, $_G;
        $fans = self::checkuser();
        if ($isworker && (empty($fans['uid']) || empty($_G['openid']))) {
            wxapp_result(1, '用户未授权无法访问，请从首页重新进入');
            exit;
        }
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $theme = Theme::getThemeByIdxcx($themeid);
        if (empty($theme['id'])) {
            wxapp_result(1, '活动入口不正确');
            exit;
        }
        if ($isworker && empty($theme['softsn'])) {
            wxapp_result(1, '软件未激活,请联系' . $_G['companyname'] . '工作人员');
            exit;
        }
        if ($isworker && $theme['softsn_status'] == 1) {
            wxapp_result(1, '版面待确认,请联系' . $_G['companyname'] . '工作人员');
            exit;
        }
        if ($isworker) {
            $msg = Worker::gethoutaistats();
        }
        if (!empty($msg) && strtolower($_P['do']) != 'myorderworkercheck') {
            wxapp_result(1, $msg);
            exit;
        }
        $config = Theme::getConfig($themeid);
        $myworker = Worker::getThemeWorkerByOpenidNew($_G['openid'], $themeid);
// var_dump($myworker);
        if (!(!$system['is_multiple_merchants'] || $config['showshop'] == 0 || ($system['is_multiple_merchants'] && $config['showshop'] == $myworker['company']))) {
            $myworker = "";
        }
        if ($isworker && (empty($myworker) || $myworker['level'] > 3)) {
            wxapp_result(1, '您不是员工,无权访问');
            exit;
        }
        $jubf['title'] = empty($theme['jubf']) ? '' : $theme['jubf'] . '-';
        $jubf['banquan'] = !empty($theme['USERCOMPANYNAME']) ? $theme['USERCOMPANYNAME'] : $_G['companyname'];

        $result = array(
            'system' => $system,
            'theme' => $theme,
            'config' => $config,
            'fans' => $fans,
            'themeid' => $themeid,
            'myworker' => $myworker,
            'jubf' => $jubf,
            'jishu' => Worker::getjishu($theme, $system),
        );
        return $result;
    }


    public function w_footmenu()
    {
        global $_P, $_G;
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $config = Theme::getConfig($themeid);
        $fans = self::checkuser();
        $worker = db_get(t_worker, array('uid' => $fans['uid']), array('id', 'level'));
        $result = array();
        if ($_G['companyname'] != '易宣软件' || empty($worker) || $worker['level'] > 3) {
            $result['is_show_service'] = 3;
        } else {
            $result['is_show_service'] = intval($config['is_show_service']);
            $result['appId'] = 'wxc920853a1ae0b77b';
            $result['path'] = 'pages/index/index?scene_param=';
        }

        wxapp_result(0, '', $result);
    }

    public function w_setbase()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $result = Worker::w_setbase($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg'], '');
        } else {
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            wxapp_result(0, '', $result);
        }
    }

    public function w_setmobile()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $result = Worker::w_setmobile($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg'], '');
        } else {
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            wxapp_result(0, '', $result);
        }
    }

    public function w_setother()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $result = Worker::w_setother($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg'], '');
        } else {
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            wxapp_result(0, '', $result);
        }
    }

    public function w_setxuni()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $result = Worker::w_setxuni($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg'], '');
        } else {
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            wxapp_result(0, '', $result);
        }
    }

//评论内容敏感信息检测
    public function Comment()
    {
        global $_P, $_G;
        $baidu_api = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=PSmuIfRZTRkzg3daPTtYeubG&client_secret=Q9n4Roe5WzwSUFETNHlHgHhtW5BfsKAr';
        $access_token = Poster::softpost($baidu_api, "", 0);
        $baidu_api = 'https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=' . $access_token->access_token;

        $result = Poster::softpost($baidu_api, array('text' => urldecode($_P['comment'])), 0);
        $data = array(
            'themeid' => intval($_P['themeid']),
            'uid' => $_G['member']['uid'],
            'msg' => $_P['comment'],
            'status' => $result->conclusion == '合规' ? 0 : 3,
        );
        $insertid = db_insert(t_comment, $data);

        if ($result->conclusion == '合规') {
            wxapp_result(0, '', 'success');
        } else {
            wxapp_result(1, '内容含有敏感信息', '');
        }
    }

    public function sharehb()
    {
        global $_G, $_P;
        $system = $_G['system'];
        $fans = self::checkuser();
        $result = Comm::sharehb($system, $fans);
        wxapp_result(0, '', $result);
    }

    public function yaoyiyao()
    {
        global $_G, $_P;
        $system = $_G['system'];
        $fans = self::checkuser();
        $result = Comm::yaoyiyao($system, $fans);
        wxapp_result(0, '', $result);
    }

    public function W_init_agent()
    {
        global $_P, $_G;
        extract(self::Isworker(false));
        $op = !empty($_P['op']) ? $_P['op'] : 'display';
        $result = Worker::w_init_agent($system, $theme, $config, $fans, $op);

        $result = array_merge($result, Common::GetWxappScene($system, $theme, $config, $fans, $theme['id']));


        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg'], '');
        } else {
            wxapp_result(0, '', $result);
        }
    }

    public function W_index()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $result = Fans::w_index($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg'], '');
        } else {
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            $result['config']['refund_limit_ip'] = $baseinfo['config']['refund_limit_ip'];
            if ($baseinfo['system']['ruanjian'] == 10) {
                require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
                require_once get_path('plugin/weike/core/model.php');
                $workerid = 0;
                if ($baseinfo['myworker']['level'] == 3) {
                    $workerid = $_G['member']['uid'];
                }
//查找微客数据：客片 客资 订单 昨日浏览  昨日打赏/昨日转发 昨日打CALL 今日浏览  今日打赏/今日转发 今日打CALL
                $result['wk_info'] = \WeikeModel::getWorkerWeikeInfo($baseinfo['theme']['id'], $baseinfo['config'], $workerid);
            }
//团人数统计
            $result['config']['tuan_num_info'] = Fans::getTuanNumInfo($baseinfo['theme']['id'], $baseinfo['myworker'], $baseinfo['config'], $baseinfo['system']);

//商家多产品记录
            if ($baseinfo['system']['mulit_products'] == 1 && $baseinfo['myworker']['level'] == 1) {

                require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
                require_once get_path('plugin/sjmulitverify/core/model.php');
                $themeid = $baseinfo['theme']['id'];
                $level = $baseinfo['myworker']['level'];
                if ($level == 1) {
                    $sjid = 0;//超级管理员
                }
                if ($level == 2 || $level == 3) {
                    $sjid = $baseinfo['myworker']['company'] ? $baseinfo['myworker']['company'] : 0;
                }
                if (!$sjid && $level == 1) {
                    $sj_list = \SjMulitVerifyModel::getShangjiaList();
                    $sj_mulit_verify = [];
                    $all_total = 0;
                    if ($sj_list) {
                        foreach ($sj_list as $k => $v) {
                            $tmp_total = (int)\SjMulitVerifyModel::getSjProductTotal($themeid, $v['id']);
                            $order_total = (int)\SjMulitVerifyModel::getOrderTotalByWhere($themeid);
                            $total = ($tmp_total * $order_total);
                            $all_total += $total;
                            $tmp_arr = ['title' => $v['name'], 'total' => $total, 'sj_id' => $v['id'], 'p_id' => 0];
                            array_push($sj_mulit_verify, $tmp_arr);
                        }
                    }
                    array_unshift($sj_mulit_verify, ['title' => '全部', 'total' => $all_total, 'sj_id' => 0, 'p_id' => 0]);
                } elseif ($sjid && ($level == 2 || $level == 3)) {
                    $sj_products = \SjMulitVerifyModel::getSjProductList($themeid, '', 1, $sjid, 0, 0);
                    $sj_mulit_verify = [];
                    $all_total = 0;
                    foreach ($sj_products as $k => $v) {
                        $sj_item_product_total = (int)\SjMulitVerifyModel::getOrderTotalByWhere($themeid);
                        $all_total += $sj_item_product_total;
                        array_push($sj_mulit_verify, ['title' => $v['name'], 'total' => $sj_item_product_total, 'p_id' => $v['id'], 'sj_id' => $sjid]);
                    }
                    array_unshift($sj_mulit_verify, ['title' => '全部', 'total' => $all_total, 'p_id' => 0, 'sj_id' => $sjid]);
                }
                $result['config']['sj_mulit_info'] = $sj_mulit_verify;
            }
//判断表单收集
            $result['system']['other_form'] = Common::get_open_other_form($baseinfo['system'], $baseinfo['config']);
//团人数统计
            $result['config']['tuan_num_info'] = Fans::getTuanNumInfo($baseinfo['theme']['id'], $baseinfo['myworker'], $baseinfo['config'], $baseinfo['system']);
//多选分类
            $dx_products = [];
            if ((($baseinfo['config']['shopstype'] == 8 && $baseinfo['config']['shops']) || ($baseinfo['config']['presale']['shopstype'] == 8 && $baseinfo['config']['presale']['shops'])) && $baseinfo['myworker']['level'] == 1) {
                $dx_cate = $baseinfo['config']['dx_cate'];
                foreach ($dx_cate as $k => $v) {
                    foreach ($v['list'] as $kk => $vv) {
                        $item = [
                            'pid' => $vv['id'],
                            'name' => $vv['name'],
                            'cate_name' => $v['name'],
                            'total' => 0
                        ];
                        array_push($dx_products, $item);
                    }
                }
                $themeid = $baseinfo['theme']['id'];
                $sql = " select count(*) as cnt from " . tablename(t_record) . " where themeid=$themeid and (status=1 or status=3) and find_in_set(";
                foreach ($dx_products as $key => $val) {
                    $where = $val['pid'] . ",`option`) ";
                    $tmp_sql = $sql . " " . $where . " ";
                    $dx_products[$key]['total'] = db_find($tmp_sql)['cnt'];
                }
            }
            if (!empty($dx_products)) {
                $result['config']['options2'] = [];
            }
            $result['config']['option5'] = $dx_products;
            wxapp_result(0, '', $result);
        }
    }


    public function W_rank()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $result = Fans::w_rank($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg'], '');
        } else {
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            wxapp_result(0, '', $result);
        }
    }

    public function W_group()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $result = Fans::W_group($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg']);
        } else {
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            wxapp_result(0, '', $result);
        }
    }

    public function W_giftRecord()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $themeid = intval($_P['themeid']);

        require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
        require_once get_path('plugin/gift/core/model.php');
        $result['list'] = \GiftModel::giftRecord($baseinfo, $themeid);
        $result['invite_gift_list'] = \GiftModel::conditionStatistics($baseinfo['system'], $baseinfo['theme']['id'], $baseinfo['myworker']);
        wxapp_result(0, 'ok', $result);
    }


    public function W_wechatgroup()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $result = Fans::W_wechatgroup($baseinfo['system'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg']);
        } else {
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            wxapp_result(0, '', $result);
        }
    }

    public function W_wechatgroup_add()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        if ($_P['op'] == 'save') {
            $result = Fans::W_wechatgroup_add($baseinfo['myworker']);
        } else {
            $result = Fans::W_wechatgroup_get($baseinfo['system']);
            $result['level'] = $baseinfo['myworker']['level'];
        }
        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg']);
        } else {
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            wxapp_result(0, '', $result);
        }
    }

    public function W_fans()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $result = Fans::W_fans($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg']);
        } else {
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            wxapp_result(0, '', $result);
        }
    }

    public function W_upload()
    {
        global $_P, $_G;
        $file = $_FILES;
        if (empty($file)) {
            return_json(1, '请上传图片！');
        }
        $wx_key = 'upload';
        $key_arr = array_keys($file);
        if (!empty($key_arr)) {
            $wx_key = $key_arr[0];
        }
        $uplad_tmp_name = $file[$wx_key]['tmp_name'];
        $uplad_name = $file[$wx_key]['name'];

        $path = ATTACHMENT_ROOT . 'poster/' . MODULE_NAME . '/';
        if (!is_dir($path)) {
            //load_func('file');
            mkdirs($path);
        }
        $new_filename = random(5) . date('mdhis') . ".jpg";
//
////移动临时文件到指定图片目录，然后上传远程后删除
        move_uploaded_file($uplad_tmp_name, $path . $new_filename);
        $remotestatus = file_remote_upload($path . $new_filename); //上传图片到远程
        if ($remotestatus['code'] != 1) {
            return_json(1, '上传图片失败！' . $remotestatus['msg']);
        } else {
            return_json(0, '', ['url' => $remotestatus['data']['url']]);
        }
    }

//表单收集
    public function W_other_form()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $worker_list = [];
        if ($baseinfo['myworker']['level'] == 1 || $baseinfo['myworker']['level'] == 2) {
            $worker_list = Otherform::getSJWorkerList($_P['themeid'], $baseinfo['myworker']['company']);
            array_unshift($worker_list, ['uid' => 0, 'username' => '全部']);
        }
        $result = Otherform::adminOtherform($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        $result['workers'] = $worker_list;
        $result['jubf'] = $baseinfo['jubf'];
        $result['jishu'] = $baseinfo['jishu'];
        $result['level'] = $baseinfo['myworker']['level'];
        wxapp_result(0, '', $result);
    }

//员工扫客户
    public function MyorderWorkerCheck()
    {
        global $_P, $_G;
        $from_type = isset($_P['from_type']) ? $_P['from_type'] : 1;
        $baseinfo = self::Isworker();
        if ($baseinfo['config']['shopstype'] == 8) {
            $from_type = 2;
        }
        if ($baseinfo['system']['mulit_products']) {
            $from_type = 3;
        }
//删除重复员工
        $themeid = intval($_P['themeid']);
        $result = Worker::MyorderWorkerCheck($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($from_type == 1) {
            if ($result['error'] == 1) {
                wxapp_result(1, $result['msg']);
            } else {
                $result['jubf'] = $baseinfo['jubf'];
                $result['jishu'] = $baseinfo['jishu'];
                wxapp_result(0, '', $result);
            }
        } elseif ($from_type == 2 || $from_type == 3) {
            if ($result['error'] == 1) {
                wxapp_result(1, $result['msg']);
            } else {
                if (isset($_P['verify_type']) && $_G['ispost']) {
                    wxapp_result(0, '', $result);
                } else {
                    $order_id = intval($_P['order_id']);
                    $themeid = intval($_P['themeid']);
                    $system = $baseinfo['system'];
                    if ($system['is_multiple_merchants']) {
                        $shop_item = db_get(t_shangjia, ['id' => $baseinfo['myworker']['company']]);
                    }
                    $record_item = db_get(t_record, ['themeid' => $themeid, 'id' => $order_id]);
                    $result['shop_item'] = $shop_item;
                    $result['record_item'] = $record_item;
                    $result['jubf'] = $baseinfo['jubf'];
                    $result['jishu'] = $baseinfo['jishu'];

                    wxapp_result(0, '', $result);
                }

            }
        }
    }

    public function W_mulitProduct()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $themeid = intval($_P['themeid']);
        $theme = $baseinfo['theme'];

        require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
        require_once get_path('plugin/sjmulitverify/core/model.php');
        $res = \SjMulitVerifyModel::formatAdminMulitInfo($baseinfo);
        $list = $res['list'];
        $uid = $res['uid'];
        $worker = $res['worker'];
        $shangjia_arr = $res['shangjia_arr'];
        $prize_arr = $res['prize_arr'];
        $sj_id = $res['sj_id'];
        $p_id = $res['p_id'];
        $page = $res['page'];
        $hasNext = $res['hasNext'];
        $page_size = $res['page_size'];
        $max_page = $res['max_page'];
        if ($list) {
            $sort = (($page - 1) * $page_size);
            foreach ($list as $key => $row) {
                $list[$key]['sort'] = $sort + ($key + 1);
                $list[$key]['created_at'] = '';
                if ($list[$key]['updated_at']) {
                    $list[$key]['created_at'] = date("m-d H:i:s", strtotime($list[$key]['updated_at']));
                }

            }
        }
        return_json(0, '', [
            'hasNext' => $hasNext, 'page_total' => $max_page, 'list' => $list, 'shangjia_arr' => $shangjia_arr,
            'prize_arr' => $prize_arr, 'jubf' => $baseinfo['jubf'], 'worker' => $worker,
            'sj_id' => $sj_id, 'p_id' => $p_id
        ]);
    }

    public function Myorder()
    {
        global $_P, $_G;
        $fans = self::checkuser();
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $theme = Theme::getThemeByIdxcx($themeid);
        if (empty($theme['id'])) {
            wxapp_result(1, '活动入口不正确');
            exit;
        }
        $config = Theme::getConfig($themeid);
        $result = Worker::Myorder($system, $theme, $config, $fans, $themeid);

        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg']);
        } else {

            $result['jubf']['title'] = empty($theme['jubf']) ? '' : $theme['jubf'] . '-';
            $result['jubf']['banquan'] = !empty($theme['USERCOMPANYNAME']) ? $theme['USERCOMPANYNAME'] : $_G['companyname'];
            $result['jishu'] = Worker::getjishu($theme, $system);
            wxapp_result(0, '', $result);
        }
    }


    public function W_order()
    {
        global $_P, $_G;
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        if ($_P['op'] == 'order_agent') {
            $_P['op'] = 'display';
            $baseinfo = self::Isworker(false);
        } else {
            $baseinfo = self::Isworker();
        }
        $result = Fans::W_order($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg']);
        } else {
            $is_lottery = $baseinfo['system']['lottery'];
            if ($is_lottery) {
                if (!($baseinfo['myworker']['level'] == 1 || $baseinfo['config']['is_view_lottery_record'] == 0)) {
                    $is_lottery = false;
                }
            }
            $result['lottery'] = $is_lottery;
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            $list = $result['list'];

            $is_shop_plan = $system['is_shop_plan'];
            if ($is_shop_plan) {

                require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
                require_once get_path('plugin/shopplan/core/model.php');

                foreach ($list as $key => $val) {
                    if (!$is_shop_plan) {
                        $plan_shop_info = [];
                    } else {
                        $plan_shop_info = \ShopplanModel::getUserPlanByUid($val['uid'], $themeid);
                    }

                    if ($plan_shop_info) {
                        $temp_str = '预约时间：' . substr($plan_shop_info['plan_at'], 0, -3);
                        array_push($list[$key]['moreinfo'], $temp_str);
                    } else {
                        if ($is_shop_plan) {
                            $temp_str = '预约时间：用户未预约';
                            array_push($list[$key]['moreinfo'], $temp_str);
                        }
                    }
                }
            }

            $result['list'] = $list;
            wxapp_result(0, '', $result);
        }
    }

    public function show_qr()
    {
        global $_P, $_G;
        extract(self::Isworker());
        $result = Worker::show_other_qr($system, $theme, $config, 'wxapp');
        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg']);
        } else {
            $result['jubf'] = $jubf;
            $result['jishu'] = $jishu;
            wxapp_result(0, '', $result);
        }
    }

//在线充值页
    public function W_recharge()
    {
        global $_P, $_G;
        $fans = self::checkuser();
        if (empty($fans['uid']) || empty($_G['openid'])) {
            return_msg('用户未授权无法访问，请从首页重新进入');
            exit;
        }
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $theme = Theme::getThemeByIdxcx($themeid);

        if ($fans['nickname'] == '新用户') {
            return wxapp_result(1, '未授权登录，请在活动页授权后，扫码重试');
        }
        if ($_P['op'] == 'pay') {
            $module_item = db_get('yx_sys_modules', ['module_name' => MODULE_NAME, 'themeid' => $themeid]);
            $module_id = empty($module_item['id']) ? '000000' : sprintf("%06d", $module_item['id']);
            $uniontid = date('YmdHis') . $module_id . random(8, 1);
            $data = array(
                'uniacid' => $_G['mpid'],
                'uniontid' => $uniontid,
                'ordertype' => 990,
                'themeid' => $themeid,
                'openid' => $_G['openid'],
                'uid' => $_G['member']['uid'],
                'username' => '后台充值',
                'status' => 0,
                'type' => 'wechat',
            );
            $data['orderfee'] = $_P['fee'];
            $data['masterid'] = 0;
            $data['detailid'] = 0;
            $billcode = getMillisecond();
            $tid = '0' . $billcode;
            $data['tid'] = $tid;
            $data['addtime'] = TIMESTAMP;
            $data['ordersn'] = $billcode;
            $orderid = Order::save($data);
            $order = Order::getByIdAndOpenid($orderid, $_G['openid']);
            $params = array('isrecharge' => false);
            if ($system['send_mode'] == 1) {
                $params ['profit_sharing'] = 'Y';
            }
            $params ['themeid'] = $order['themeid'];
            $params ['uniontid'] = $order['uniontid'];
            $params ['tid'] = $tid;
            $params ['user'] = $_G['openid'];
            $params ['fee'] = $_P['fee'];
            $params ['title'] = '活动款';
            $params ['ordersn'] = $billcode;
            $params ['virtual'] = false;
            $params ['orderid'] = $order['id'];
            $pay_params = $this->pay($params);
// $data['params']=$pay_params ;
            if (is_error($pay_params)) {
                return wxapp_result(1, '支付失败，请重试', $pay_params);
            }
            return wxapp_result(0, '', $pay_params);
        } else {
            $result = Comm::getRechargeFee($system, $theme, $themeid);
            $jubf['title'] = empty($theme['jubf']) ? '' : $theme['jubf'] . '-';
            $jubf['banquan'] = !empty($theme['USERCOMPANYNAME']) ? $theme['USERCOMPANYNAME'] : $_G['companyname'];
            $result['jubf'] = $jubf;
            $result['jishu'] = Worker::getjishu($theme, $system);
            wxapp_result(0, '', $result);
        }
    }

    public function GetMyInfo()
    {
        global $_G, $_P;
        $fans = self::checkuser();
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $theme = Theme::getThemeByIdxcx($themeid);
        $themeid = intval($_P['themeid']);
        $config = Theme::getConfig($themeid);
        $result = Record::getMyInfo($system, $theme, $config, $fans);
        return_json($result['error'], $result['msg'], $result['data']);
    }

    public function W_myinfo()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $result = Fans::w_myinfo($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);

        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg']);
        } else {
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            wxapp_result(0, '', $result);
        }
    }

    public function W_report()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $result = Worker::w_report($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);

        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg']);
        } else {
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            wxapp_result(0, '', $result);
        }
    }

    public function W_report_ren()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $result = Worker::w_report_ren($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);

        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg']);
        } else {
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            wxapp_result(0, '', $result);
        }
    }

    public function SaveLog()
    {
        global $_P, $_G;
        $data = array(
            'e' => Util::zCode($_P['e']),
            'url' => $_P['url'],
            'postdata' => Util::zCode($_P['postdata']),
        );
        yxlog($data, '小程序网络请求错');
        wxapp_result(0, '保存成功');
    }

    public function W_ranktuan()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
//    $result = Worker::w_ranktuan($baseinfo['system'],$baseinfo['theme'],$baseinfo['config'],$baseinfo['myworker']);

        $page = $page_index = max(1, intval($_P['page']));
        $page_size = 20;
        $page_start = ($page_index - 1) * $page_size;
        $hasNext = true;


        $result = Worker::w_ranktuan($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker'], $page_start, $page_size, $page_index);
        $page_total = $result['page_total'];
        if ($page >= $page_total) {
            $hasNext = false;
        }
        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg']);
        } else {
            $result['hasNext'] = $hasNext;
            $result['wlistindex'] = 0;
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            wxapp_result(0, '', $result);
        }
    }

    public function W_example()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        if ($baseinfo['config']['examplestyle'] == 1) {
            $result = array('error' => 2, 'msg' => "跳转支付凭证样式");
            wxapp_result(0, '', $result);
            return;
        }
        $result = Worker::w_example($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        $result['transaction_id'] = mb_substr($result['transaction_id'], 0, 16, 'utf-8') . "******" . mb_substr($result['transaction_id'], 22, 6, 'utf-8');
        $result['uniontid'] = mb_substr($result['uniontid'], 0, 16, 'utf-8') . "******" . mb_substr($result['uniontid'], 22, 6, 'utf-8');

        if ($baseinfo['config']['isexampleqr'] != 2) {
            if (!empty($result['workerid'])) {
                $fansinfo = db_find('SELECT * FROM ' . tablename(t_fans) . '
WHERE themeid = :themeid AND uid = :uid', array(':themeid' => $baseinfo['themeid'], ':uid' => $result['workerid']));
                if (empty($fansinfo['poster_qrcode'])) {
                    $scene = MODULE_NAME . "-" . $baseinfo['themeid'] . "-" . $result['workerid'] . "-" . $baseinfo['theme']['softkey'];
                    $result['qrcode'] = Poster::CreateScene($baseinfo['system'], $scene, $baseinfo['config'], 'pages/index/index');
                } else {
                    $result['qrcode'] = $fansinfo['poster_qrcode'];
                }
            }
        }
        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg']);
        } else {
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            $result['error'] = 0;
            wxapp_result(0, '', $result);
        }
    }


    public function W_orderdetail()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $baseinfo['myworker']['level'] == 3;
        $detail = $_P['detail'];
        if ($detail == 'bargain') {
            $result = Worker::W_bargaindetail($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
        }
        if ($detail == 'game' || $detail == 'koi') {
            $themeid = $baseinfo['themeid'];
            $uid = intval($_P['id']);
            $page_size = 20;
            $page_index = max(1, intval($_P['page']));
            $page_start = ($page_index - 1) * $page_size;
            if ($baseinfo['myworker']['level'] != '1' && $uid == 0) {
                $workerid = $_G['member']['uid'];
            }
        }
        if ($detail == 'game') {
            $type = trim($_P['type']);
            $list = Game::formatLifeInfo($themeid, $uid, $page_start, $page_size, $type, $workerid);
            $result = $list;
            $fans = Fans::getById($uid, $themeid);
            $result['avatar'] = $fans['avatar'];
            $result['nickname'] = $fans['username'] != '新用户' && !empty($fans['username']) ? $fans['username'] : $fans['nickname'];
        } elseif ($detail == 'koi') {
            $result = array();
            if ($baseinfo['config']['game_on_off'] == 1) {
                $themeid = $baseinfo['config']['five_themeid'];
            } else {
                $themeid = $baseinfo['themeid'];
            }
            $list = Koi::getKoiUserFlagList($themeid, '', '', '', '', '', $page_start, $page_size, '', $uid, $workerid);
            $result['total'] = Koi::getKoiUserFlagList($themeid, '', '', '', '', '', $page_start, $page_size, '', $uid, $workerid, true);
            if (!empty($list)) {
                foreach ($list as $index => $item) {
                    if (!empty($uid)) {
                        $list[$index]['name'] = mb_substr($item['name'], 0, 22, 'utf-8');
                    } else {
                        $list[$index]['name'] = mb_substr($item['name'], 0, 4, 'utf-8');
                    }
                }
            }
            $result['list'] = $list;
        }

        if ($detail == 'game' || $detail == 'koi') {
            $fans = Record::getLastGroupByUidhexiao($uid, $themeid, false);
            if (empty($fans)) {
                $fans = Fans::getById($uid, $themeid);
            }
            $newfans = array();
            $newfans['avatar'] = $fans['avatar'];
            $newfans['nickname'] = $fans['nickname'];
            $newfans['username'] = $fans['username'];
            $newfans['mobile'] = $fans['mobile'];
            $result['fans'] = $newfans;
            if ($page_index * $page_size >= $result['total']) {
                $result['hasNext'] = false;
            } else {
                $result['hasNext'] = true;
            }
            $result['page'] = $page_index;
        }

        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg']);
        } else {
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            wxapp_result(0, '', $result);
        }
    }

    public function W_orderedit()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();

        if ($_P['op'] == 'searchtuan') {
            $themeid = intval($_P['themeid']);
            $result = Record::searchtuan($baseinfo['config'], $themeid);

            $tuanlistnew = array();
            if (!empty($result['tuanlist'])) {
                foreach ($result['tuanlist'] as $index => $row) {
                    $tuanid = $row['id'] + 10000;
                    $tuanlistnew[$index]['name'] = $row['username'] . "【" . $row['mobile'] . "】已有" . $row['renshu'] . "人 团号" . $tuanid;
                    $tuanlistnew[$index]['value'] = $row['id'];
                }
            }
            $result['tuanlist'] = $tuanlistnew;
            wxapp_result(0, '', $result);
        }
//多选分类数据处理
        if ($_G['ispost'] && $baseinfo['config']['shopstype'] == 8 && $baseinfo['config']['shops'] && $_P['op'] == 'save' && $baseinfo['config']['form_five_qty'] == 1) {
//获取当前操作的订单
            if ($_P['option']) {
                $tmp_option = explode(',', rtrim($_P['option'], ','));
                if (is_array($tmp_option)) {
                    $recordid = $_P['id'];
                    $tmp_record_item = db_get(t_record, ['id' => $recordid, 'themeid' => $themeid]);
                    if ($tmp_record_item) {
//取出历史数据
                        $record_option = $tmp_record_item['option'];
                        $tmp_record_option = explode(',', rtrim($record_option, ','));
                        $diff_arr_add = array_diff($tmp_option, $tmp_record_option);//变动的项
                        $diff_arr_del = array_diff($tmp_record_option, $tmp_option);//取消的项
//新增项减少库存
                        if ($diff_arr_add && is_array($diff_arr_add)) {
                            foreach ($diff_arr_add as $k1 => $v1) {
                                $check_item = db_get(t_form_five_user_flag, ['order_id' => $recordid, 'form_item_id' => $v1, 'user_id' => $tmp_record_item['uid'], 'themeid' => $themeid]);
                                if (!$check_item) {
                                    $insertid = db_insert(t_form_five_user_flag, ['order_id' => $recordid, 'form_item_id' => $v1, 'user_id' => $tmp_record_item['uid'], 'themeid' => $themeid]);
                                }
                            }
                        }
//修改项增加库存
                        if ($diff_arr_del && is_array($diff_arr_del)) {
                            foreach ($diff_arr_del as $k2 => $v2) {
                                $check_item = db_get(t_form_five_user_flag, ['order_id' => $recordid, 'form_item_id' => $v2, 'user_id' => $tmp_record_item['uid'], 'themeid' => $themeid]);
                                if ($check_item) {
                                    db_delete(t_form_five_user_flag, ['order_id' => $recordid, 'form_item_id' => $v2, 'user_id' => $tmp_record_item['uid'], 'themeid' => $themeid]);
                                }
                            }
                        }
                    }
                }
            }
        }

        $result = Fans::W_orderedit($baseinfo['system'], $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
//多选分类
        if (($baseinfo['config']['shops'] && $baseinfo['config']['shopstype'] == 8) || ($baseinfo['config']['presale']['shops'] && $baseinfo['config']['presale']['shopstype'] == 8)) {

            $selectedshops = $result['record']['shops'];
            if ($selectedshops) {
//数据兼容处理
                if (strstr($selectedshops, '|')) {
                    $selectedshops = rtrim($selectedshops, '|');
                    $selectedshops = explode("|", $selectedshops);
                }
                if (is_string($selectedshops) && strstr($selectedshops, ',')) {
                    $selectedshops = rtrim($selectedshops, ',');
                    $selectedshops = explode(",", $selectedshops);
                }
                $dx_cate = $baseinfo['config']['dx_cate'];
                foreach ($dx_cate as $k => $v) {
                    foreach ($v['list'] as $kk => $vv) {
                        if ($vv['is_default'] == 1) {
                            $dx_cate[$k]['list'][$kk]['checked'] = 1;
                        }
                        foreach ($selectedshops as $kkk => $vvv) {
                            if ($vv['id'] == $vvv) {
                                $dx_cate[$k]['list'][$kk]['checked'] = 1;
                            }
                        }
                    }
                }
                $result['config']['option'] = $dx_cate;
            }
        }
//小程序默认请求处理返回 并且超管
        if ($_P['op'] == '' && $result['level'] == 1) {
            $tmp_wlist = array_values($result['wlist']);
            $tmp_wlist_index = $result['wlist_index'];
            foreach ($tmp_wlist as $k => $v) {
                if ($v['value'] == $tmp_wlist_index) {
                    $result['wlist_index'] = $k;
                    break;
                }
            }
            $result['wlist'] = $tmp_wlist;
        }
        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg']);
        } else {
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            wxapp_result(0, '', $result);
        }
    }

    public function W_input()
    {
        global $_P, $_G;
        $fans = self::checkuser();
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $config = Theme::getConfig($themeid);
        if ($config['presale']['presalePrice'] > 1 && TIMESTAMP > $config['yukuantime']) {
            $system['bottom_jiage'] = $config['presale']['presalePrice'] - 1;
        }
        $record_selected_arr = [];
        if ($_P['op'] == 'bangding') {
            $result = W_input::bangding($system, $config, $fans);
        } elseif ($_P['op'] == "getinfo") {
            $myworker = Worker::getThemeWorkerByOpenid($_G['openid'], $themeid, 1);
            $theme = Theme::getThemeByIdxcx($themeid);
            $result = W_input::input($system, $theme, $config, $myworker);
            $baseinfo = array();
            $baseinfo['jubf']['title'] = '定单确认';
            $baseinfo['jubf']['banquan'] = '';
            if (empty($myworker)) {
                $baseinfo['jishu'] = '';
            } else {
                $baseinfo['jishu'] = Worker::getjishu($theme, $system);
            }
            if (empty($result['level'])) {
                $sql = "SELECT id,username FROM " . tablename(t_record) . "
WHERE (uid = :uid or uid_other =:uid) and (status > 0) and id <> '" . $result['record']['id'] . "'";
                $isbangding = db_select($sql, array(":uid" => $_G['member']['uid']));
                $isbukuan = $config['yukuan'] > 0 && (TIMESTAMP > $config['yukuantime']) ? true : false;
                if ($config['wuxian'] == 0 && (count($isbangding) > 1 && $isbukuan || count($isbangding) == 1 && !$isbukuan)) {
                    $dingdangid = $isbangding[0]['id'] + 9000;
                    wxapp_result(1, "此微信已绑定定单:" . $dingdangid . "-" . $isbangding[0]['username']);
                }
            }
            $record_selected_arr = explode(',', $result['record']['option']);
        } else {
            $baseinfo = self::Isworker();
            if (empty($_P['op']) && ($system['bottom_jiage'] > 0)) {
                $result['op'] = 'group_name';
                $result['config'] = 'group_name';
                $result['level'] = $baseinfo['myworker']['level'];
                $result['group_name'] = Record::getGroupName($baseinfo['config']);
            } else {
                $result = W_input::input($system, $baseinfo['theme'], $baseinfo['config'], $baseinfo['myworker']);
            }
//车牌号 类型9修改为0文本输入
            if (isset($result['config']['addresstype']) && $result['config']['addresstype'] == 9) {
                $result['config']['addresstype'] = 0;
            }
            if (isset($result['config']['addresstype']) && $result['config']['formtwotype'] == 9) {
                $result['config']['formtwotype'] = 0;
            }
            if (isset($result['config']['addresstype']) && $result['config']['shopstype'] == 9) {
                $result['config']['shopstype'] = 0;
            }
        }

//3.5.2 临时性解决多选分类 单个分类下的 多选项无法选择问题 目前已在dev小程序分支修复
// 因老版小程序无法发版 暂且将小程序中线下订单录入 设计到多选分类隐藏，小程序提交后pc后台修改
        if ($baseinfo['config']['shopstype'] == 8 || $config['shopstype'] == 8) {
//增加逻辑判断  如果都为单选正常使用  如果存在多选  取消多选分类显示 改为后台设置
            $cate_product = $result['config']['options'] ? $result['config']['options'] : $config['dx_cate'];
            $only_select_one = true;
            if ($cate_product) {
                foreach ($cate_product as $k => $v) {
                    $item_list = $v['list'];
                    foreach ($item_list as $k1 => $v1) {
                        if ($record_selected_arr) {
                            if (in_array($v1['id'], $record_selected_arr)) {
                                $cate_product[$k]['list'][$k1]['checked'] = true;
                            }
                        }
                        $cate_product[$k]['list'][$k1]['name'] = $v['name'] . '-' . $v1['name'];
                    }
                }
            }
            $result['config']['options'] = $result['config']['shopsoptions'] = $cate_product;
//            $result['config']['shops']='';
//            $result['config']['options']=[];

            $accountlist = Modules::getPlatformByAppid($system['wxapp']);

            if (strstr($accountlist['name'], "新版") == false) {
//老版本小程序 处理
                $result['config']['shops'] = '';
                $result['config']['options'] = [];
            }
        }
//注释区间代码块为 临时性代码  部分活动升级 新版本小程序已修复

        if ($result['error'] == 1) {
            wxapp_result(1, $result['msg']);
        } else {

            $auth_mode = intval($system['auth_mode']);
            if ($system['wxapp_demo'] == 1 || $fans['status'] == 2) {
                $auth_mode = 0;
            }
            $avatar_default = 'https://css2020.yixuan.net/2020css/yx2020/images/question.png';
            if ($config['getavatar'] > 0 && ($fans['avatar'] != '' && $fans['avatar'] != $avatar_default && $fans['nickname'] != '新用户' && $fans['nickname'] != '微信用户')) {
                $config['getavatar'] = 0;
            }

            $result['auth'] = array(
                'mode' => $auth_mode,  //0为小程序本身授权，1为借用H5授权，2为借用小程序授权
                'server' => $system['auth_server'],
                'getavatar' => $config['getavatar'],
                'getmobile' => $config['getmobile'],
            );
            $result['pinpailogo'] = $config['pinpailogo'];
            $result['theme_jubf'] = $theme['jubf'];
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            wxapp_result(0, '', $result);
        }
    }


    public function W_verify()
    {
        require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
        require_once get_path('plugin/lottery/core/model.php');
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $op = isset($_P['op']) ? $_P['op'] : 'display';
        if (!$baseinfo) {
            if ($op == 'display') {
                return_json(1, '非员工无法访问', '');
                die();
            } elseif ($op == 'sure_verify' && $_G['ispost']) {
                return_json(1, '非员工无法访问', '');
            }
        }
        $themeid = $baseinfo['theme']['id'];
        $uid = $_P['fromuid'];
        $f_id = $_P['f_id'];
        $workerid = $_P['uid'];
        if (!$workerid) {
            $workerid = $_G['member']['uid'];
        }
        if ($op == 'display') {
            $lt_flag = \LotteryModel::getLtFlagAndPrizeInfoByWhere($themeid, $uid, $f_id, false);
            if (!$lt_flag) {
                return_json(1, '该用户待核销奖品不存在，请检查后重试', '');
            }

            $info = [
                'img' => $lt_flag['small_img'],
                'gift_title' => $lt_flag['title'] . '-' . $lt_flag['name'],
                'username' => $lt_flag['username'],
                'mobile' => $lt_flag['mobile'],
                'f_id' => $lt_flag['f_id'],
                'uid' => $uid,
                'themeid' => $themeid,
                'notice' => ''
            ];
//判断唯一性兑换
            if (!$baseinfo['config']['yx_lt_convert_only']) {
                $user_chekced_falg = \LotteryModel::getUserFlags($themeid, $uid, 4);
                if ($user_chekced_falg > 0) {
                    $info['notice'] = '已核销其他奖品，无法继续核销';
                }
            }
            if ($lt_flag && $lt_flag['status'] == 4) {
                $r = Worker::getWokerName($baseinfo['system'], $themeid, $lt_flag['workerid']);
                $workername = $r['workername'];
                $info['notice'] = '由员工[' . $workername . '],于' . $lt_flag['updated_at'] . '完成核销';
            }
            return_json(0, '', $info);
        } elseif ($op == 'sure_verify') {
//判断唯一性兑换
            if (!$baseinfo['config']['yx_lt_convert_only']) {
                $user_chekced_falg = \LotteryModel::getUserFlags($themeid, $uid, 4);
                if ($user_chekced_falg > 0) {
                    return_json(1, '已核销其他奖品，当前无法核销', '');
                }
            }
            $f_id = $_P['f_id'];
//修改订单
            $where = ['f_id' => $f_id, 'themeid' => $themeid, 'uid' => $uid, 'status' => 3];
            $data = ['status' => 4, 'workerid' => $workerid];
            $res = \LotteryModel::editLtFlagItem($where, $data);
            if (!$baseinfo['config']['yx_lt_convert_only'] && $res) {
//修改其他的奖项为失效
                \LotteryModel::editUserLtFlagLose($uid, $themeid, 0, 0);
            }
            if (empty($res)) {
                return_json(1, '该奖品未兑换或已核销，请检查后重试', '');
            } else {
                return_json(0, '核销成功', '');
            }
        }
    }


    /**
     * Desc:摇一摇多礼品核销
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/4/1 13:21
     */
    public function W_gifts()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $fans = self::checkuser();
        $op = isset($_P['op']) ? $_P['op'] : 'display';
        if (!$baseinfo) {
            if ($op == 'display') {
                return_json(1, '非员工无法访问', '');
                die();
            } elseif ($op == 'sure_verify' && $_G['ispost']) {
                return_json(1, '非员工无法访问', '');
            }
        }
        $themeid = $baseinfo['theme']['id'];
        $uid = $_P['fromuid'];
        $f_id = $_P['f_id'];
        $workerid = $_P['uid'];
        if (!$workerid) {
            $workerid = $_G['member']['uid'];
        }
        $config = Theme::getConfig($themeid);
        if ($op == 'display') {
            $lt_flag = Yxgifts::getGiftItem($themeid, $fans, $f_id, $config);
            if (!$lt_flag) {
                return_json(1, '该用户待核销礼品不存在，请检查后重试', '');
            }

            $info = [
                'img' => $lt_flag['img'],
                'gift_title' => $lt_flag['gift_title'],
                'username' => $lt_flag['username'],
                'mobile' => $lt_flag['mobile'],
                'f_id' => $lt_flag['f_id'],
                'uid' => $uid,
                'themeid' => $themeid,
                'notice' => ''
            ];
            if ($lt_flag && $lt_flag['status'] == 4) {
                $r = Worker::getWokerName($baseinfo['system'], $themeid, $lt_flag['workerid']);
                $workername = $r['workername'];
                $info['notice'] = '由员工[' . $workername . '],于' . $lt_flag['updated_at'] . '完成核销';
            }
            return_json(0, '', $info);
        } elseif ($op == 'sure_verify') {
            $f_id = $_P['f_id'];
//修改订单
            $where = ['id' => $f_id, 'themeid' => $themeid, 'status' => 3];
            $data = ['status' => 4, 'workerid' => $workerid];
            $res = Yxgifts::editFanGift($where, $data);
            if (empty($res)) {
                return_json(1, '该礼品未兑换或已核销，请检查后重试', '');
            } else {
                return_json(0, '核销成功', '');
            }
        }
    }


//公司排名
    public function W_shoprank()
    {
        global $_G, $_P;
        $baseinfo = self::Isworker();
        $fans = self::checkuser();
        $themeid = intval($_P['themeid']);
        $paixu = $_P['paixu'];
        $from = isset($_P['from']) ? $_P['from'] : 'mobile';
        $system = $_G['system'];
        $theme = Theme::getThemeById($themeid);
        $config = Theme::getConfig($themeid);
        $res = Worker::companyRank($theme, $config, $system, $paixu);
        if ($res['error'] == 1) {
            return_json(1, $res['msg'], '');
        } else {
            return_json(0, $res['msg'], $res['data']);
        }
    }

//团队排名
    public function W_grouprank()
    {
        global $_G, $_P;
        $baseinfo = self::Isworker();
        $fans = self::checkuser();
        $themeid = intval($_P['themeid']);
        $paixu = $_P['paixu'];
        $do = 'X_grouprank';
        $from = isset($_P['from']) ? $_P['from'] : 'mobile';
        $system = $_G['system'];
        $theme = Theme::getThemeById($themeid);
        $config = Theme::getConfig($themeid);
        $soft = $_P['soft'];
        $res = Worker::teamRank($theme, $config, $system, $paixu);
        if ($res['error'] == 1) {
            return_json(1, $res['msg'], '');
        } else {
            return_json(0, $res['msg'], $res['data']);
        }
    }

//个人排名
    public function W_workerrank()
    {
        global $_G, $_P;
        $baseinfo = self::Isworker();
        $fans = self::checkuser();
        $themeid = intval($_P['themeid']);
        $paixu = $_P['paixu'];
        $do = 'X_grouprank';
        $from = isset($_P['from']) ? $_P['from'] : 'mobile';
        $system = $_G['system'];
        $theme = Theme::getThemeById($themeid);
        $config = Theme::getConfig($themeid);
        $soft = $_P['soft'];
        $res = Worker::workerRank($theme, $config, $system, $paixu);
        if ($res['error'] == 1) {
            return_json(1, $res['msg'], '');
        } else {
            return_json(0, $res['msg'], $res['data']);
        }
    }

    public function W_lottery()
    {

        require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
        require_once get_path('plugin/lottery/core/model.php');
        global $_G, $_P;
        $fans = self::checkuser();
        $themeid = intval($_P['themeid']);
        $system = $_G['system'];
        $theme = Theme::getThemeById($themeid);
        $config = Theme::getConfig($themeid);
        $baseinfo = self::Isworker();

        $uid = isset($_P['uid']) ? $_P['uid'] : '';
        $p_id = $_P['p_id'];
        $op = $_P['op'] ? $_P['op'] : "all";
        if (!$uid) {
            $op = 'all';
        }
        $page = $_P['page'] ? $_P['page'] : 1;
        $hasNext = true;
        $page_index = max(1, intval($page));
        $page_size = 20;
        $page_start = ($page_index - 1) * $page_size;

        $prize_arr = \LotteryModel::getPrizeFlagCount($themeid, true);
        if ($op == 'all' || ($op != 'all' && $uid)) {
            $lists = \LotteryModel::getDefaultLtList($themeid, 0, $p_id, 0, 0, $uid);
            $list = \LotteryModel::getDefaultLtList($themeid, 0, $p_id, $page_start, $page_size, $uid);
            foreach ($list as $key => $row) {
                $list[$key]['sort'] = $key + 1;
                if ($row['from_type'] == 'red_envelope') {
                    $item = \LotteryModel::getRpFlagItem(['themeid' => $themeid, 'f_id' => $row['f_id']]);
                    if ($item && $row['red_envelopes_amount_min'] != $row['red_envelopes_amount_max']) {
                        $list[$key]['title'] = '现金红包' . $item['amount'] . '元';
                    }
                }
                $list[$key]['created_at'] = date("m-d H:i:s", strtotime($list[$key]['created_at']));
            }
            $max_page = ceil(count($lists) / $page_size);
            if ($max_page <= $page) {
                $hasNext = false;
            }
            if ($_G['ispost']) {
                $temp_html_taun = '';
                $sort = (($page - 1) * $page_size);
                foreach ($list as $key => $val) {
                    $list[$key]['sort'] = $sort + ($key + 1);
                }
            }
        } else {
            $hasNext = false;
            $max_page = 1;
            $list = [];
        }


        return_json(0, '', ['hasNext' => $hasNext, 'page_total' => $max_page, 'list' => $list, 'prize_arr' => $prize_arr, 'jubf' => $baseinfo['jubf']]);
    }

    public function W_ltexample()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $themeid = intval($_P['themeid']);
        $theme = $baseinfo['theme'];

        require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
        require_once get_path('plugin/lottery/core/model.php');
        if ($_G['ispost']) {
//post请求

            $res = \LotteryModel::dummyConvert($baseinfo['config'], $baseinfo['theme'], $baseinfo['system'], 'wxapp');
            $res['jubf'] = $baseinfo['jubf'];
            $res['jishu'] = $baseinfo['jishu'];
            return_json(0, '操作成功', $res);
        }
    }

    /**
     * Desc:红包核销
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/14 9:32 下午
     */
    public function W_redrainVerify()
    {
        require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
        require_once get_path('plugin/redrain/core/model.php');
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $op = isset($_P['op']) ? $_P['op'] : 'display';
        if (!$baseinfo) {
            if ($op == 'display') {
                return_json(1, '非员工无法访问', '');
                die();
            } elseif ($op == 'sure_verify' && $_G['ispost']) {
                return_json(1, '非员工无法访问', '');
            }
        }
        $themeid = $baseinfo['theme']['id'];
        $uid = $_P['fromuid'];
        $f_id = $_P['f_id'];
        $workerid = $_P['uid'];
        if (!$workerid) {
            $workerid = $_G['member']['uid'];
        }
        $from_fans = \RedRainModel::getFansInfoByWhere(['themeid' => $themeid, 'uid' => $uid]);
        if ($op == 'display') {
            $flag = \RedRainModel::getUserRedRainFlagItemByWhere(['themeid' => $themeid, 'uid' => $uid, 'id' => $f_id]);
            if (!$flag) {
                return_json(1, '该用户待核销红包不存在，请检查后重试', '');
            }
            if ($flag && $flag['status'] == 3) {
                return_json(1, '该用户已存在其他提现', '');
            }
//判断当前红包是否过期
            $now_time = date("Y-m-d H:i:s", time());
            $redrain_validity = $baseinfo['config']['redrain_validity'];
            $current_flag_overdue = false;//当前是否过期
            $has_more_max = false;//有比当前核销红包更大的红包
            if ($flag['status'] == 2) {
                $current_flag_overdue = true;
            } else {
                if ($redrain_validity > 0) {
                    $validate_time = date("Y-m-d H:i:s", strtotime("+$redrain_validity hour", strtotime($flag['created_at'])));
                    if ($validate_time < $now_time) {
                        $current_flag_overdue = true;
                    }
                }
            }


//获我的最高可用的红包记录
            $my_redrain_base_info = \RedRainModel::getUserCanUseRedRainFlag($themeid, $from_fans['uid'], $baseinfo['config'], $baseinfo['system']);
            if ($my_redrain_base_info && ($my_redrain_base_info['id'] != $flag['id'])) {
                $has_more_max = true;//判断是否存在比验证的更大的可用红包
            }
//助力记录
            $my_friend_info = \RedRainModel::getUserFriendInfo($themeid, $from_fans, $baseinfo['config']);
//红包记录
            $my_redrain_flag = \RedRainModel::getFrontUserRedRainList($themeid, $from_fans['uid'], $baseinfo['config'], $baseinfo['system']);
//机会记录
            $my_chance_flag = \RedRainModel::getFrontUserChanceList($themeid, $from_fans['uid']);
            $rules = $baseinfo['config']['redrain_rules'];


            $info = [
                'current_flag' => $flag,
                'current_flag_overdue' => $current_flag_overdue,//当前是否过期
                'has_more_max' => $has_more_max,//存在比当前红包更大的红包
                'username' => $from_fans['username'],
                'nickname' => $from_fans['nickname'],
                'avatar' => $from_fans['avatar'],
                'mobile' => $from_fans['mobile'],
                'scansum' => $from_fans['scansum'],
                'tuijian' => $from_fans['tuijian'],
                'responsum' => $from_fans['responsum'],
                'f_id' => $flag['id'],
                'uid' => $uid,
                'themeid' => $themeid,
                'my_redrain_base_info' => $my_redrain_base_info,
                'my_friend_info' => $my_friend_info,
                'my_redrain_flag' => $my_redrain_flag,
                'my_chance_flag' => $my_chance_flag,
                'rules' => $rules,
                'redrain_mode' => $baseinfo['system']['redrain'],
                'workername' => ''
            ];
            if ($flag && $flag['status'] == 1 && $flag['worker_id']) {
                $r = Worker::getWokerName($baseinfo['system'], $themeid, $flag['worker_id']);
                $workername = $r['workername'];
                $info['workername'] = $workername;
//                $info['notice'] = '由员工['.$workername.'],于'.$flag['updated_at'].'完成核销';
            }
            return_json(0, '', $info);
        } elseif ($op == 'sure_verify') {
            $f_id = $_P['f_id'];
//修改订单
            $res = \RedRainModel::apiUseRedRainFlag($themeid, $from_fans, $f_id, $baseinfo['system'], $workerid);
            if (empty($res)) {
                return_json(1, '该红包核销失败，请检查后重试', '');
            } else {
                return_json(0, '核销成功', '');
            }
        }
    }

    /**
     * Desc:代言列表以及审核
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/1/21 11:34 上午
     */
    public function W_daiyan()
    {
        require_once YX_PLUGIN_CORE . 'inc/plugin_model.php';
        require_once get_path('plugin/daiyan/core/model.php');
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $op = (isset($_P['op']) && $_P['op']) ? $_P['op'] : 'display';
        $op2 = (isset($_P['op2']) && $_P['op2']) ? $_P['op2'] : '';
        if (!$baseinfo) {
            if ($op == 'display') {
                return_json(1, '非员工无法访问', '');
                die();
            } elseif ($op == 'sure_verify' && $_G['ispost']) {
                return_json(1, '非员工无法访问', '');
            }
        }
        $themeid = $baseinfo['theme']['id'];
        $uid = $_P['fromuid'];
        $workerid = $_P['uid'];
        if (!$workerid) {
            $workerid = $_G['member']['uid'];
        }
        if ($op == 'display') {
            $can_next = false;
            $status = isset($_P['status']) ? $_P['status'] : '';
            $page_index = max(1, intval($_P['page']));
            $page_size = 5;
            $page_start = ($page_index - 1) * $page_size;

            $search_data = isset($_P['searchtxt']) ? $_P['searchtxt'] : '';
            if ($search_data) {
                $search_data = '%' . $search_data . '%';
            }
            $status_list = DaiYanModel::getDaiYanStatusArr($themeid);
            $sort = isset($_P['sort']) ? $_P['sort'] : 'daiyan_liked';
            $target_uid = isset($_P['target_uid']) ? $_P['target_uid'] : '';
            if (!$target_uid) {
                $op2 = '';
            }
            if ($op2 == 'comment') {
//                代言下评论
                $lists = DaiYanModel::getDaiYanReturnListOrSearch($themeid, $target_uid, $search_data, 0, 0);
                $list = DaiYanModel::getDaiYanReturnListOrSearch($themeid, $target_uid, $search_data, $page_start, $page_size);
                foreach ($list as $key => $val) {
                    $r = Worker::getWokerName($baseinfo['system'], $themeid, $val['worker_id']);
                    $list[$key]['admin_name'] = $r['workername'];
                }
            } else {
//                代言
                if (!$search_data) {
                    $lists = DaiYanModel::getDaiYanList($themeid, $status, $sort, 0, 0);
                    $list = DaiYanModel::getDaiYanList($themeid, $status, $sort, $page_start, $page_size);
                } else {
                    $lists = DaiYanModel::searchDaiYanList($themeid, $search_data, 0, 0, '', '');
                    $list = DaiYanModel::searchDaiYanList($themeid, $search_data, $page_start, $page_size, '', '');
                }


                foreach ($list as $key => $val) {
                    if ($val['daiyan_worker_id']) {
                        $r = Worker::getWokerName($baseinfo['system'], $themeid, $val['daiyan_worker_id']);
                        $list[$key]['admin_name'] = $r['workername'];
                    } else {
                        $list[$key]['admin_name'] = '';
                    }


                    $list[$key]['return_total'] = DaiYanModel::getDaiYanRefundTotal($themeid, $val['uid']);
                    $list[$key]['liked_total'] = DaiYanModel::getFriendHelpFlagTotal($themeid, $val['uid']);
                }
            }

            $max_page = ceil(count($lists) / $page_size);
            if ($max_page > $page_index) {
                $can_next = true;
            }

            $info = [
                'hasNext' => $can_next,
                'status_list' => $status_list,
                'jishu' => self::getjishu($baseinfo['theme'], $baseinfo['system']),
                'jubf' => self::getjubf($baseinfo['theme'], $baseinfo['system']),
                'list' => $list,
                'page' => $page_index,
                'totalPage' => $max_page,
                'totalSize' => count($lists),
            ];
//            if ($flag && $flag['status']==1 && $flag['worker_id']){
//                $r = Worker::getWokerName($baseinfo['system'],$themeid,$flag['worker_id']);
//                $workername=$r['workername'];
//                $info['workername'] = $workername;
////                $info['notice'] = '由员工['.$workername.'],于'.$flag['updated_at'].'完成核销';
//            }
            return_json(0, '', $info);
        } elseif ($op == 'audit') {
            $f_id = $_P['f_id'];
            $type = $_P['type'];
            $status = $_P['audit_status'];
            if ($type == 'daiyan') {
                $where = ['themeid' => $themeid, 'id' => $f_id];
                $update_data = ['daiyan_status' => $status, 'daiyan_worker_id' => $workerid];
                $update_res = DaiYanModel::editDaiYanItem($where, $update_data);
            } else {
                $where = ['themeid' => $themeid, 'id' => $f_id];
                $update_data = ['status' => $status, 'worker_id' => $workerid];
                $update_res = DaiYanModel::editDaiYanComment($where, $update_data);
            }
            if (empty($update_res)) {
                return_json(1, '审核失败，请检查后重试', '');
            } else {
                return_json(0, '审核成功', '');
            }
        }
    }

//获取页面底部技术信息
    protected function getjishu($theme, $system)
    {
        if ($theme['yixuanbanquan'] != '1') {
            if (empty($theme['USERJISHU'])) {
                $jishu['txt'] = $system['s']['yixuanjishu'];
                $jishu['mobile'] = $system['s']['yixuanphone'];
            } else {
                $jishu['txt'] = html_entity_decode($theme['USERJISHU'], ENT_QUOTES);
                $jishu['mobile'] = str_replace("tel:", "", $theme['USERURL']);
            }
        }
        return $jishu;
    }

    protected function getjubf($theme, $system)
    {
        global $_G;
        $jubf = [];
        $jubf['title'] = empty($theme['jubf']) ? '' : $theme['jubf'] . '-';
        $jubf['banquan'] = !empty($theme['USERCOMPANYNAME']) ? $theme['USERCOMPANYNAME'] : $_G['companyname'];
        return $jubf;
    }

    /**
     * 投诉接口
     */
    public function Complain()
    {
        global $_P, $_G;
        $system = $_G['system'];
        $themeid = $_P['themeid'];
        $op = isset($_P['op']) ? $_P['op'] : 'home';
        $fans = self::checkuser();

        if ($op == 'home' || $op == 'question' || $op == 'newquestion' || $op == 'homenewquestion') {
            $content = Complain::getTypeList($system, $themeid);
            $content['complain'] = Complain::getComplain($fans, $themeid);
            wxapp_result(0, 'ok', $content);
        } elseif ($op == 'save') {
            $fans = self::checkuser();
            $r = Complain::saveComplain($system, $fans);
            wxapp_result($r['errcode'], 'ok', $r);
        }
    }

    public function Getrank()
    {
        global $_P, $_G;
        $fans = self::checkuser();
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $theme = Theme::getThemeByIdxcx($themeid);
        $config = Theme::getConfig($themeid);
        if ($_P['isindex'] == 1) {
            if ($config['rank_order_new'] > 0) {
                $config['rank_order'] = $config['rank_order_new'];
                $config['rank_show'] = $config['rank_show_new'];
                $config['rank_user_type'] = $config['rank_user_type_new'];
                $config['rank_top_img'] = $config['rank_top_img_new'];
            }
        }
        $r = Record::getrank($system, $theme, $config, $themeid);
        if ($r['errcode'] == 1) {
            wxapp_result(1, $r['msg']);
        } else {
            $result = $r['data'];
            $result['jishu'] = Worker::getjishu($theme, $system, $config['pinpailogo']);
            wxapp_result(0, '', $result);
        }
    }

    /**
     * 用户扫码退
     */
    public function X_refundCode()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        if ($baseinfo['config']['refund_limit_ip'] != 1) {
//更新此时工作人员IP地址:$_G['clientip']
            db_update(t_fans, ['ip' => $_G['clientip']], ['uid' => $_G['member']['uid'], 'themeid' => $baseinfo['theme']['id']]);
            if ($baseinfo['myworker']['refunderm']) {
                $result['refunderm'] = $baseinfo['myworker']['refunderm'];
            } else {
//调用生成小程序码
                $scene = MODULE_NAME . "-" . $baseinfo['theme']['id'] . "-" . $_G['member']['uid'] . "-" . $baseinfo['theme']['softkey'] . "-0";
                $url = 'Worker/pages/w_refund/w_refund';
//                $url = 'Worker/pages/w_index/w_index';
                $qrimg = Poster::CreateScene($baseinfo['system'], $scene, $baseinfo['config'], $url);
                $qrimg = str_replace('http:', 'https:', $qrimg);
//将二维码更新写入worker表
                db_update(t_worker, ['refunderm' => $qrimg], ['uid' => $_G['member']['uid'], 'themeid' => $baseinfo['theme']['id']]);
                $result['refunderm'] = $qrimg;
                $result['tips'] = "客户需要退款时，为创造一次和客户见面沟通的机会，了解客户退款的真正原因，再次压单成交；此功能是客户必须到店连接wifi扫码才可以退款；";
            }
            $result['username'] = '：' . $baseinfo['myworker']['username'];
            wxapp_result(0, '', $result);
        } else {
            wxapp_result(1, '到店退款码未开启');
        }
    }

    /**
     * 用户扫码退
     */
    public function W_userRefund()
    {
        global $_P, $_G;
        $system = $_G['system'];
        $themeid = $_P['themeid'];
        $config = Theme::getConfig($themeid);
        $theme = Theme::getThemeById($themeid);
        $fromuid = isset($_P['fromuid']) ? intval($_P['fromuid']) : 0;
        $fans = self::checkuser();
        $uid = $fans['uid'];
        if (!$uid) {
            return_json(2, '未检测到您的用户信息，重新扫码试试');
        }
//查找员工信息
        $workerinfo = db_get(t_worker, ['uid' => $fromuid, 'themeid' => $themeid]);
        if (!$workerinfo) {
            return_json(1, '未找到工作人员信息', '');
        }
        $themyrecord = Record::getLastGroupByUidhexiao($_G['member']['uid'], $themeid, true);
        if (empty($themyrecord)) {
            return_json(3, '未查到您的付款定单，立即去报名吧', '');
        }
//是否限制退款IP，命名为：refund_limit_ip
        $fromuserinfo = db_get(t_fans, ['uid' => $fromuid, 'themeid' => $themeid]);
        if ($fromuserinfo['ip'] != $_G['clientip']) {
            return_json(1, '需到店连接商家内部安全网络方可进行退款', '');
        }
        $opuser = '扫【' . $workerinfo['username'] . '】的码退';
        if ($config['refund_limit_ip'] == 1) {
            return_json(1, '功能未开启，无权操作', '');
        } else if ($config['refund_limit_ip'] == 2) {
            $ret = Record::refund($themyrecord['id'], $themeid, $theme, $system, $config, $opuser);
            if (isset($ret['error'])) {
                if ($ret['error'] == 0) {
                    $ret['error'] = 3;
                }
                return_json($ret['error'], $ret['msg'], '');
            } else {
                return_json(1, '退款失败：未知错误', '');
            }
        } else {
            yxlog($themyrecord['username'] . $themyrecord['mobile'] . $opuser, '扫码退款');
            $state = db_update(t_record, array('isrefund' => 7, 'refundtime' => TIMESTAMP), array('id' => $themyrecord['id']));
            $msg = '您的申请退款已提交，等待申核';
            return_json(1, $msg, '');
        }
    }

//扫码退款页面
    public function W_myRefundInfo()
    {
        try {
            global $_P, $_G;
            $fans = self::checkuser();
            $uid = $fans['uid'];
            $themeid = $_P['themeid'];
            $_C = $config = Theme::getConfig($themeid);
            $theme = Theme::getThemeById($themeid);
            $system = $_G['system'];
            if (!$uid) {
                return_json(2, '未检测到您的用户信息，重新扫码试试');
            }
//查找员工信息
            $fromuid = isset($_P['fromuid']) ? intval($_P['fromuid']) : 0;
            $fromuserinfo = db_get(t_worker, ['uid' => $fromuid, 'themeid' => $themeid]);
            if (!$fromuserinfo) {
                return_json(2, '未找到工作人员信息', '');
            }
            if ($fromuid == $uid) {
                db_update(t_fans, ['ip' => $_G['clientip']], ['uid' => $_G['member']['uid'], 'themeid' => $themeid]);
                return_json(2, '您的网络信息已同步');
            }
            $themyrecord = Record::getAttendByThemeIdAndOpenid($themeid, $_G['openid'], false);
            if (empty($themyrecord)) {
                return_json(3, '未查到您的付款定单，立即去报名吧');
            }
            $themyorder = Order::getPayOrderByRIdZhifude($themyrecord['id']);
            $themyrecord['mobile'] = mb_substr($themyrecord['mobile'], 0, 3, 'utf-8') . '****' . mb_substr($themyrecord['mobile'], -4, 4, 'utf-8');

            $themyorder['realfee'] = sprintf("%.2f", $themyorder['realfee']);

            $result = array();

            $themyorder = $result['themyorder'] = $themyorder;
            $themyrecord = $result['themyrecord'] = $themyrecord;
            $themyorder['add_time'] = date('Y-m-d H:i:s', $themyorder['addtime']);
            $themyorder['pay_time'] = date('Y-m-d H:i:s', $themyorder['paytime']);

            return_json(0, '', ['themyorder' => $themyorder, 'themyrecord' => $themyrecord, 'fans' => $fans]);
        } catch (Exception $e) {
            return_json(1, $e->getMessage());
        }
    }

    /**
     * Desc:客资表单收集
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/4/27 10:40
     */
    public function Otherform()
    {
        global $_P, $_G;
        $system = $_G['system'];
        $themeid = $_P['themeid'];
        $op = isset($_P['op']) ? $_P['op'] : 'display';
        $fans = self::checkuser();
        $fileds = json_decode(html_entity_decode(stripslashes($_P['filed'])), true);
        $workerid = isset($_P['workerid']) ? $_P['workerid'] : 0;
        if ($fans && $themeid) {
            $res = Otherform::submitCusInfo($system, $themeid, $fans, $workerid, $fileds);
            return_json($res['error'], $res['msg'], $res['data']);
        } else {
            return_json(1, '提交失败', []);
        }
    }

//客户开新团
    public function NewGroup()
    {
        global $_P, $_G;
        $system = $_G['system'];
        $themeid = intval($_P['themeid']);
        $config = Theme::getConfig($themeid);
        $theme = Theme::getThemeById($themeid);
        $UserLevel = Theme::getUserLevel($_G['member']['uid'], $themeid);
        $url = $_G['siteroot'] . createMobileUrl('index', array("themeid" => $themeid, "fromuid" => $_G['member']['uid'], "soft" => $theme['softkey']));
        if ($config['newgroup'] == 1 && $UserLevel == 3 || $UserLevel == 4) {
            $themyrecord = Record::getRecordByUid($_G['member']['uid'], $themeid);
            $r = Record::newtuan($system, $themyrecord['id'], $themeid, $config);
//获取定单信息：theMyRecord
            $fans = Fans::getById($_G['member']['uid'], $themeid);
            extract(Record::getTheMyRecord($system, $fans, $themyrecord['id'], $config, $themeid));
//获取要显示的团明细
            extract(Record::getShowRecord($system, $recordid, $config, $themeid));
            $mygroup = Theme::myGroupInfo($system, $config, $nowgroupneednum, $detaillist, $showrecord, $num_arr, $themeid);
            return_json(0, '成功开新团', $mygroup);
        } else {
            return_json(1, '没有权限开新团');
        }
    }

//
    public function W_exportData()
    {
        global $_P, $_G;
        $themeid = intval($_P['themeid']);
        if (!$themeid) {
            return_json(1, '参数错误1');
        }

        $uid = intval($_P['uid']);
        if (!$uid) {
            return_json(1, '参数错误2');
        }

        $worker_info = db_find('SELECT id,status,level,download_auth,download_key,download_key_time FROM ' . tablename(t_worker) . '   WHERE themeid = :themeid AND uid = :uid', array(':themeid' => $themeid, ':uid' => $uid));
        if (empty($worker_info)) {
            return_json(1, '数据不存在');
        }

        if ($worker_info['level'] != 1) {
            return_json(1, '无权限导出1');
        }

        if ($worker_info['download_auth'] != 1) {
            return_msg('无权限导出2');
        }

        $system = $_G['system'];
        $config = Theme::getConfig($themeid);
        $status = $_P['status'] ? $_P['status'] : -10;
        $type = isset($_P['type']) ? $_P['type'] : -1;;
        $yukuan = isset($_P['yukuan']) ? $_P['yukuan'] : 0;

        $time = Record::getSearchTime();
        $start_time = $_P['starttime'] ? $_P['starttime'] : date('Y-m-d H:i', $time['starttime']);
        $end_time = $_P['endtime'] ? $_P['endtime'] : date('Y-m-d H:i', $time['endtime']);
        $nowoker = intval($_P['noworker']);
        unset($_P['fromuid']);
        if (isset($_P['export_type'])) {
            $list = Recordbase::allList($themeid, $system, $config, $_P);
            return_json(0, '', ['url' => $list]);
        } else {
            $tuannum = $_P['tuannum'];
            if (!$tuannum) {
                $tuannum = array();
            }
            extract(Record::getSearchTime());
            extract(Recordbase::getCondition($system, $config, $themeid, $start_time, $end_time, $id));
            $btn_info = Recordbase::btn($themeid, $system, $config, $_P, $condition);
            $btn_info['wlist'] = array_values($btn_info['wlist']);
            $list = Recordbase::allList($themeid, $system, $config, $_P);
            $total = $list['total'];
            $export_total = $list['export_total'];
            $export_total_arr = $list['export_total_arr'];
            $export_num = $list['export_num'];
            return_json(0, '',
                ['btn_info' => $btn_info,
                    'total' => $total,
                    'export_num' => $export_num,
                    'export_total' => $export_total,
                    'export_total_arr' => $export_total_arr,
                    'starttime' => $start_time,
                    'endtime' => $end_time
                ]);
        }
    }

//删除excel
    public function W_delexcel()
    {
        global $_P, $_G;
        $url = $_P['url'];
        Recordbase::deleteExcel($url);
    }

//分销数据
    public function W_fenxiao()
    {
        global $_P, $_G;
        $baseinfo = self::Isworker();
        $op = (isset($_P['op']) && $_P['op']) ? $_P['op'] : 'display';
        $themeid = intval($_P['themeid']);
        $system = $_G['system'];
        $config = Theme::getConfig($themeid);
        if ($op == 'display') {
            if (!$themeid) {
                return_json(1, '参数错误1');
            }
            $btns = Common::btns($themeid, $system, $config);
            $result = Common::fxLists($themeid, $system, $config);
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            $result['btns'] = $btns;
            wxapp_result(0, '查询成功', $result);
        } elseif ($op == 'detail') {
            $fans = Fans::getById($_P['uid'], $themeid);
            $result = Common::getInfo($themeid, $system);
            $result['fans'] = $fans;
            $result['jubf'] = $baseinfo['jubf'];
            $result['jishu'] = $baseinfo['jishu'];
            wxapp_result(0, '', $result);
        } elseif ($op == 'check') {
            $id = $_P['id'];
            $result = Common::checkFee($id, $themeid, $system);
            return $result;
        }
    }

    public function Wx()
    {
        global $_G, $_P;
        $r = isset($_P['r']) ? trim($_P['r']) : '';
        if (!$r) {
            //r参数不存在提示模块不存在
            die('<H1>插件功能参数错误2:</H1>');
        }
        $_P['from'] = 'wxapp';
        $route = new PluginRoute();
        $route->run(false);
    }
}
